Python django.db.models.query_utils.DeferredAttribute() Examples

The following are 10 code examples of django.db.models.query_utils.DeferredAttribute(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.query_utils , or try the search function .
Example #1
Source File: __init__.py    From bioforum with MIT License 6 votes vote down vote up
def contribute_to_class(self, cls, name, private_only=False):
        """
        Register the field with the model class it belongs to.

        If private_only is True, create a separate instance of this field
        for every subclass of cls, even if cls is not an abstract model.
        """
        self.set_attributes_from_name(name)
        self.model = cls
        if private_only:
            cls._meta.add_field(self, private=True)
        else:
            cls._meta.add_field(self)
        if self.column:
            # Don't override classmethods with the descriptor. This means that
            # if you have a classmethod and a field with the same name, then
            # such fields can't be deferred (we don't have a check for this).
            if not getattr(cls, self.attname, None):
                setattr(cls, self.attname, DeferredAttribute(self.attname, cls))
        if self.choices:
            setattr(cls, 'get_%s_display' % self.name,
                    partialmethod(cls._get_FIELD_display, field=self)) 
Example #2
Source File: test_docstrings.py    From sphinxcontrib-django with Apache License 2.0 6 votes vote down vote up
def test_model_fields(self):
        lines = []
        simple_model_path = 'sphinxcontrib_django.tests.test_docstrings.SimpleModel'
        if django.VERSION < (3, 0):
            obj = DeferredAttribute(field_name='dummy_field', model=simple_model_path)
        else:
            model = import_string(simple_model_path)
            obj = DeferredAttribute(field=model._meta.get_field('dummy_field'))

        docstrings._improve_attribute_docs(obj, '{}.dummy_field'.format(simple_model_path), lines)
        self.assertEqual(
            lines,
            [
                "**Model field:** dummy field",
            ],
        ) 
Example #3
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def contribute_to_class(self, cls, name, private_only=False):
        """
        Register the field with the model class it belongs to.

        If private_only is True, create a separate instance of this field
        for every subclass of cls, even if cls is not an abstract model.
        """
        self.set_attributes_from_name(name)
        self.model = cls
        if private_only:
            cls._meta.add_field(self, private=True)
        else:
            cls._meta.add_field(self)
        if self.column:
            # Don't override classmethods with the descriptor. This means that
            # if you have a classmethod and a field with the same name, then
            # such fields can't be deferred (we don't have a check for this).
            if not getattr(cls, self.attname, None):
                setattr(cls, self.attname, DeferredAttribute(self.attname))
        if self.choices:
            setattr(cls, 'get_%s_display' % self.name,
                    partialmethod(cls._get_FIELD_display, field=self)) 
Example #4
Source File: base.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def __reduce__(self):
        """
        Provides pickling support. Normally, this just dispatches to Python's
        standard handling. However, for models with deferred field loading, we
        need to do things manually, as they're dynamically created classes and
        only module-level classes can be pickled by the default path.
        """
        if not self._deferred:
            return super(Model, self).__reduce__()
        data = self.__dict__
        defers = []
        for field in self._meta.fields:
            if isinstance(self.__class__.__dict__.get(field.attname),
                    DeferredAttribute):
                defers.append(field.attname)
        model = self._meta.proxy_for_model
        return (model_unpickle, (model, defers), data) 
Example #5
Source File: resource_data.py    From rotest with MIT License 6 votes vote down vote up
def __getattribute__(cls, key):
        if int(DJANGO_VERSION[0]) == 1 and int(DJANGO_VERSION[1]) < 10:
            try:
                field_pointer = super(DataBase, cls).__getattribute__(key)

            except AttributeError:
                if '_meta' in vars(cls) and \
                        key in (field.name for field in cls._meta.fields):

                    field_pointer = DeferredAttribute(key, None)

                else:
                    raise

        else:
            field_pointer = super(DataBase, cls).__getattribute__(key)

        if field_pointer is not None and \
                isinstance(field_pointer, (DeferredAttribute,
                                           ForwardManyToOneDescriptor)):

            return DataPointer(field_ref=field_pointer)

        return field_pointer 
Example #6
Source File: apps.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def ready(self):
        post_migrate.connect(
            create_permissions,
            dispatch_uid="django.contrib.auth.management.create_permissions"
        )
        last_login_field = getattr(get_user_model(), 'last_login', None)
        # Register the handler only if UserModel.last_login is a field.
        if isinstance(last_login_field, DeferredAttribute):
            from .models import update_last_login
            user_logged_in.connect(update_last_login, dispatch_uid='update_last_login')
        checks.register(check_user_model, checks.Tags.models)
        checks.register(check_models_permissions, checks.Tags.models) 
Example #7
Source File: __init__.py    From python with Apache License 2.0 5 votes vote down vote up
def contribute_to_class(self, cls, name, private_only=False, virtual_only=NOT_PROVIDED):
        """
        Register the field with the model class it belongs to.

        If private_only is True, a separate instance of this field will be
        created for every subclass of cls, even if cls is not an abstract
        model.
        """
        if virtual_only is not NOT_PROVIDED:
            warnings.warn(
                "The `virtual_only` argument of Field.contribute_to_class() "
                "has been renamed to `private_only`.",
                RemovedInDjango20Warning, stacklevel=2
            )
            private_only = virtual_only
        self.set_attributes_from_name(name)
        self.model = cls
        if private_only:
            cls._meta.add_field(self, private=True)
        else:
            cls._meta.add_field(self)
        if self.column:
            # Don't override classmethods with the descriptor. This means that
            # if you have a classmethod and a field with the same name, then
            # such fields can't be deferred (we don't have a check for this).
            if not getattr(cls, self.attname, None):
                setattr(cls, self.attname, DeferredAttribute(self.attname, cls))
        if self.choices:
            setattr(cls, 'get_%s_display' % self.name,
                    curry(cls._get_FIELD_display, field=self)) 
Example #8
Source File: models.py    From algoliasearch-django with MIT License 5 votes vote down vote up
def _should_really_index(self, instance):
        """Return True if according to should_index the object should be indexed."""
        if self._should_index_is_method:
            is_method = inspect.ismethod(self.should_index)
            try:
                count_args = len(inspect.signature(self.should_index).parameters)
            except AttributeError:
                # noinspection PyDeprecation
                count_args = len(inspect.getargspec(self.should_index).args)

            if is_method or count_args is 1:
                # bound method, call with instance
                return self.should_index(instance)
            else:
                # unbound method, simply call without arguments
                return self.should_index()
        else:
            # property/attribute/Field, evaluate as bool
            attr_type = type(self.should_index)
            if attr_type is DeferredAttribute:
                attr_value = self.should_index.__get__(instance, None)
            elif attr_type is str:
                attr_value = getattr(instance, self.should_index)
            elif attr_type is property:
                attr_value = self.should_index.__get__(instance)
            else:
                raise AlgoliaIndexError('{} should be a boolean attribute or a method that returns a boolean.'.format(
                    self.should_index))
            if type(attr_value) is not bool:
                raise AlgoliaIndexError("%s's should_index (%s) should be a boolean" % (
                    instance.__class__.__name__, self.should_index))
            return attr_value 
Example #9
Source File: __init__.py    From python2017 with MIT License 5 votes vote down vote up
def contribute_to_class(self, cls, name, private_only=False, virtual_only=NOT_PROVIDED):
        """
        Register the field with the model class it belongs to.

        If private_only is True, a separate instance of this field will be
        created for every subclass of cls, even if cls is not an abstract
        model.
        """
        if virtual_only is not NOT_PROVIDED:
            warnings.warn(
                "The `virtual_only` argument of Field.contribute_to_class() "
                "has been renamed to `private_only`.",
                RemovedInDjango20Warning, stacklevel=2
            )
            private_only = virtual_only
        self.set_attributes_from_name(name)
        self.model = cls
        if private_only:
            cls._meta.add_field(self, private=True)
        else:
            cls._meta.add_field(self)
        if self.column:
            # Don't override classmethods with the descriptor. This means that
            # if you have a classmethod and a field with the same name, then
            # such fields can't be deferred (we don't have a check for this).
            if not getattr(cls, self.attname, None):
                setattr(cls, self.attname, DeferredAttribute(self.attname, cls))
        if self.choices:
            setattr(cls, 'get_%s_display' % self.name,
                    curry(cls._get_FIELD_display, field=self)) 
Example #10
Source File: base.py    From luscan-devel with GNU General Public License v2.0 4 votes vote down vote up
def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        """
        Saves the current instance. Override this in a subclass if you want to
        control the saving process.

        The 'force_insert' and 'force_update' parameters can be used to insist
        that the "save" must be an SQL insert or update (or equivalent for
        non-SQL backends), respectively. Normally, they should not be set.
        """
        using = using or router.db_for_write(self.__class__, instance=self)
        if force_insert and (force_update or update_fields):
            raise ValueError("Cannot force both insert and updating in model saving.")

        if update_fields is not None:
            # If update_fields is empty, skip the save. We do also check for
            # no-op saves later on for inheritance cases. This bailout is
            # still needed for skipping signal sending.
            if len(update_fields) == 0:
                return

            update_fields = frozenset(update_fields)
            field_names = set()

            for field in self._meta.fields:
                if not field.primary_key:
                    field_names.add(field.name)

                    if field.name != field.attname:
                        field_names.add(field.attname)

            non_model_fields = update_fields.difference(field_names)

            if non_model_fields:
                raise ValueError("The following fields do not exist in this "
                                 "model or are m2m fields: %s"
                                 % ', '.join(non_model_fields))

        # If saving to the same database, and this model is deferred, then
        # automatically do a "update_fields" save on the loaded fields.
        elif not force_insert and self._deferred and using == self._state.db:
            field_names = set()
            for field in self._meta.fields:
                if not field.primary_key and not hasattr(field, 'through'):
                    field_names.add(field.attname)
            deferred_fields = [
                f.attname for f in self._meta.fields
                if f.attname not in self.__dict__
                   and isinstance(self.__class__.__dict__[f.attname],
                                  DeferredAttribute)]

            loaded_fields = field_names.difference(deferred_fields)
            if loaded_fields:
                update_fields = frozenset(loaded_fields)

        self.save_base(using=using, force_insert=force_insert,
                       force_update=force_update, update_fields=update_fields)