Python django.db.models.fields.FieldDoesNotExist() Examples

The following are 30 code examples of django.db.models.fields.FieldDoesNotExist(). 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.fields , or try the search function .
Example #1
Source File: mixins.py    From django-accounting with MIT License 6 votes vote down vote up
def get_queryset(self):
        queryset = super().get_queryset()
        queryset = (queryset
            .select_related(
                'organization')
            .prefetch_related(
                'lines',
                'lines__tax_rate'))

        try:
            # to raise the exception
            self.model._meta.get_field_by_name('client')
            queryset = queryset.select_related('client')
        except FieldDoesNotExist:
            pass

        try:
            # to raise the exception
            self.model._meta.get_field_by_name('payments')
            queryset = queryset.prefetch_related('payments')
        except FieldDoesNotExist:
            pass

        return queryset 
Example #2
Source File: table_views.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_field_or_method_label(self, model, field_name):
        resource_label = self._get_resource_label(model, field_name)
        if resource_label is not None:
            return resource_label
        else:
            try:
                field = model._meta.get_field(field_name)
                if field.auto_created and (field.one_to_many or field.many_to_many):
                    return (
                        getattr(field.field, 'reverse_verbose_name', None) or
                        field.related_model._meta.verbose_name_plural
                    )
                elif field.auto_created and field.one_to_one:
                    return (
                        getattr(field.field, 'reverse_verbose_name', None) or
                        field.related_model._meta.verbose_name
                    )
                else:
                    return field.verbose_name
            except FieldDoesNotExist:
                method = get_class_method(model, field_name)
                return getattr(method, 'short_description', pretty_name(field_name)) 
Example #3
Source File: mptt_tags.py    From indrz with GNU General Public License v3.0 6 votes vote down vote up
def render(self, context):
        # Let any VariableDoesNotExist raised bubble up
        args = [self.node.resolve(context)]

        if self.foreign_key is not None:
            app_label, model_name, fk_attr = self.foreign_key.split('.')
            cls = apps.get_model(app_label, model_name)
            if cls is None:
                raise template.TemplateSyntaxError(
                    _('drilldown_tree_for_node tag was given an invalid model: %s') %
                    '.'.join([app_label, model_name])
                )
            try:
                cls._meta.get_field(fk_attr)
            except FieldDoesNotExist:
                raise template.TemplateSyntaxError(
                    _('drilldown_tree_for_node tag was given an invalid model field: %s') % fk_attr
                )
            args.extend([cls, fk_attr, self.count_attr, self.cumulative])

        context[self.context_var] = drilldown_tree_for_node(*args)
        return '' 
Example #4
Source File: views.py    From wagtailmodeladmin with MIT License 6 votes vote down vote up
def get_ordering_field(self, field_name):
        """
        Returns the proper model field name corresponding to the given
        field_name to use for ordering. field_name may either be the name of a
        proper model field or the name of a method (on the admin or model) or a
        callable with the 'admin_order_field' attribute. Returns None if no
        proper model field name can be matched.
        """
        try:
            field = self.opts.get_field(field_name)
            return field.name
        except FieldDoesNotExist:
            # See whether field_name is a name of a non-field
            # that allows sorting.
            if callable(field_name):
                attr = field_name
            elif hasattr(self.model_admin, field_name):
                attr = getattr(self.model_admin, field_name)
            else:
                attr = getattr(self.model, field_name)
            return getattr(attr, 'admin_order_field', None) 
Example #5
Source File: options.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def get_field_by_name(self, name):
        """
        Returns the (field_object, model, direct, m2m), where field_object is
        the Field instance for the given name, model is the model containing
        this field (None for local fields), direct is True if the field exists
        on this model, and m2m is True for many-to-many relations. When
        'direct' is False, 'field_object' is the corresponding RelatedObject
        for this field (since the field doesn't have an instance associated
        with it).

        Uses a cache internally, so after the first access, this is very fast.
        """
        try:
            try:
                return self._name_map[name]
            except AttributeError:
                cache = self.init_name_map()
                return cache[name]
        except KeyError:
            raise FieldDoesNotExist('%s has no field named %r'
                    % (self.object_name, name)) 
Example #6
Source File: base.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def serializable_value(self, field_name):
        """
        Returns the value of the field name for this instance. If the field is
        a foreign key, returns the id value, instead of the object. If there's
        no Field object with this name on the model, the model attribute's
        value is returned directly.

        Used to serialize a field's value (in the serializer, or form output,
        for example). Normally, you would just access the attribute directly
        and not use this method.
        """
        try:
            field = self._meta.get_field_by_name(field_name)[0]
        except FieldDoesNotExist:
            return getattr(self, field_name)
        return getattr(self, field.attname) 
Example #7
Source File: utils.py    From django-admirarchy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_field_exists(self, field_name: str):
        """Implements field exists check for debugging purposes.

        :param field_name:

        """
        if not settings.DEBUG:
            return

        try:
            self.lookup_opts.get_field(field_name)

        except FieldDoesNotExist as e:
            raise AdmirarchyConfigurationError(e)


######################################################## 
Example #8
Source File: mixins.py    From django-accounting with MIT License 6 votes vote down vote up
def _restrict_fields_choices(self, model, organization, fields):
        for source in fields:
            field, m, direct, m2m = model._meta.get_field_by_name(source)
            rel = field.rel
            if not rel:
                # next field
                continue

            rel_model = rel.to
            try:
                rel_model._meta.get_field_by_name(self.relation_name)
            except FieldDoesNotExist:
                # next field
                continue

            form_field = fields[source]
            form_field.queryset = (form_field.choices.queryset
                .filter(**{self.relation_name: organization})) 
Example #9
Source File: views.py    From wagtailmodeladmin with MIT License 5 votes vote down vote up
def get_dict_for_field(self, field_name):
        """
        Return a dictionary containing `label` and `value` values to display
        for a field.
        """
        try:
            field = self.model._meta.get_field(field_name)
        except FieldDoesNotExist:
            field = None
        return {
            'label': self.get_field_label(field_name, field),
            'value': self.get_field_display_value(field_name, field),
        } 
Example #10
Source File: models.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_model_field_by_name(model, field_name):
    try:
        return model._meta.get_field_by_name(field_name)[0]
    except FieldDoesNotExist:
        return None 
Example #11
Source File: __init__.py    From django-is-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_field_from_model_or_none(model, field_name):
    try:
        return model._meta.get_field(field_name)
    except (FieldDoesNotExist, AttributeError):
        return None 
Example #12
Source File: mixins.py    From django-accounting with MIT License 5 votes vote down vote up
def get_queryset(self):
        queryset = super().get_queryset()
        queryset = queryset.select_related('organization')

        try:
            # to raise the exception
            self.model._meta.get_field_by_name('client')
            queryset = queryset.select_related('client')
        except FieldDoesNotExist:
            pass

        return queryset 
Example #13
Source File: utils.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def get_field_parts(model, field_name):
    """
    Get the field parts that represent the traversable relationships from the
    base ``model`` to the final field, described by ``field_name``.

    ex::

        >>> parts = get_field_parts(Book, 'author__first_name')
        >>> [p.verbose_name for p in parts]
        ['author', 'first name']

    """
    parts = field_name.split(LOOKUP_SEP)
    opts = model._meta
    fields = []

    # walk relationships
    for name in parts:
        try:
            field = opts.get_field(name)
        except FieldDoesNotExist:
            return None

        fields.append(field)
        if isinstance(field, RelatedField):
            opts = remote_model(field)._meta
        elif isinstance(field, ForeignObjectRel):
            opts = field.related_model._meta

    return fields 
Example #14
Source File: serializers.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
        """
        Returns all the model fields that are being mapped to by fields
        on the serializer class.
        Returned as a dict of 'model field name' -> 'model field'.
        Used internally by `get_uniqueness_field_options`.
        """
        model = getattr(self.Meta, 'model')
        model_fields = {}

        for field_name in field_names:
            if field_name in declared_fields:
                # If the field is declared on the serializer
                field = declared_fields[field_name]
                source = field.source or field_name
            else:
                try:
                    source = extra_kwargs[field_name]['source']
                except KeyError:
                    source = field_name

            if '.' in source or source == '*':
                # Model fields will always have a simple source mapping,
                # they can't be nested attribute lookups.
                continue

            try:
                field = model._meta.get_field(source)
                if isinstance(field, DjangoModelField):
                    model_fields[source] = field
            except FieldDoesNotExist:
                pass

        return model_fields

    # Determine the validators to apply... 
Example #15
Source File: utils.py    From sal with Apache License 2.0 5 votes vote down vote up
def get_model_at_related_field(model, attr):
    """
    Looks up ``attr`` as a field of ``model`` and returns the related model class.  If ``attr`` is
    not a relationship field, ``ValueError`` is raised.

    """

    try:
        field, direct = get_field(model._meta, attr)
    except FieldDoesNotExist:
        raise

    if not direct:
        if hasattr(field, 'related_model'):  # Reverse relationship
            # -- Django >=1.8 mode
            return field.related_model
        elif hasattr(field, "model"):
            # -- Django <1.8 mode
            return field.model

    if hasattr(field, 'rel') and field.rel:  # Forward/m2m relationship
        return field.rel.to

    if hasattr(field, 'field'):  # Forward GenericForeignKey in Django 1.6+
        return field.field.rel.to

    raise ValueError("{0}.{1} ({2}) is not a relationship field.".format(model.__name__, attr,
                                                                         field.__class__.__name__)) 
Example #16
Source File: utils.py    From sal with Apache License 2.0 5 votes vote down vote up
def resolve_orm_path(model, orm_path):
    """
    Follows the queryset-style query path of ``orm_path`` starting from ``model`` class.  If the
    path ends up referring to a bad field name, ``django.db.models.fields.FieldDoesNotExist`` will
    be raised.

    """

    bits = orm_path.split('__')
    endpoint_model = reduce(get_model_at_related_field, [model] + bits[:-1])
    if bits[-1] == 'pk':
        field = endpoint_model._meta.pk
    else:
        field, _ = get_field(endpoint_model._meta, bits[-1])
    return field 
Example #17
Source File: columns.py    From sal with Apache License 2.0 5 votes vote down vote up
def resolve_source(self, model, source):
        # Try to fetch the leaf attribute.  If this fails, the attribute is not database-backed and
        # the search for the first non-database field should end.
        if hasattr(source, "__call__"):
            return None
        try:
            return resolve_orm_path(model, source)
        except FieldDoesNotExist:
            return None 
Example #18
Source File: views.py    From wagtailmodeladmin with MIT License 5 votes vote down vote up
def has_related_field_in_list_display(self):
        for field_name in self.list_display:
            try:
                field = self.opts.get_field(field_name)
            except FieldDoesNotExist:
                pass
            else:
                if isinstance(field, models.ManyToOneRel):
                    return True
        return False 
Example #19
Source File: expressions.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def prepare_leaf(self, node, query, allow_joins):
        if not allow_joins and LOOKUP_SEP in node.name:
            raise FieldError("Joined field references are not permitted in this query")

        field_list = node.name.split(LOOKUP_SEP)
        if (len(field_list) == 1 and
            node.name in query.aggregate_select.keys()):
            self.contains_aggregate = True
            self.cols.append((node, query.aggregate_select[node.name]))
        else:
            try:
                dupe_multis = False if self.reuse is None else True
                field, source, opts, join_list, last, _ = query.setup_joins(
                    field_list, query.get_meta(), query.get_initial_alias(),
                    dupe_multis, can_reuse=self.reuse)
                col, _, join_list = query.trim_joins(source, join_list, last, False)
                if self.reuse is not None:
                    self.reuse.update(join_list)
                self.cols.append((node, (join_list[-1], col)))
            except FieldDoesNotExist:
                raise FieldError("Cannot resolve keyword %r into field. "
                                 "Choices are: %s" % (self.name,
                                                      [f.name for f in self.opts.fields]))

    ##################################################
    # Vistor methods for final expression evaluation #
    ################################################## 
Example #20
Source File: models.py    From django-softdelete-it with MIT License 5 votes vote down vote up
def get_un_soft_deleted_objects(self, collector):
        '''filter all those objects from collector which are already
        soft-deleted'''
        for model, instances in collector.data.items():
            try:
                if model._meta.get_field("deleted"):
                    collector.data[model] = set(filter(lambda x: not x.deleted,
                                                instances))
            except FieldDoesNotExist:
                # if deleted field does not exist in model, do nothing
                pass
        return collector 
Example #21
Source File: ideascube_tags.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def field_verbose_name(model, name):
    try:
        field = model._meta.get_field(name)
    except FieldDoesNotExist:
        return ''
    else:
        return field.verbose_name 
Example #22
Source File: options.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def get_field(self, name, many_to_many=True):
        """
        Returns the requested field by name. Raises FieldDoesNotExist on error.
        """
        to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
        for f in to_search:
            if f.name == name:
                return f
        raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name)) 
Example #23
Source File: query_utils.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __get__(self, instance, owner):
        """
        Retrieves and caches the value from the datastore on the first lookup.
        Returns the cached value.
        """
        from django.db.models.fields import FieldDoesNotExist
        non_deferred_model = instance._meta.proxy_for_model
        opts = non_deferred_model._meta

        assert instance is not None
        data = instance.__dict__
        if data.get(self.field_name, self) is self:
            # self.field_name is the attname of the field, but only() takes the
            # actual name, so we need to translate it here.
            try:
                f = opts.get_field_by_name(self.field_name)[0]
            except FieldDoesNotExist:
                f = [f for f in opts.fields
                     if f.attname == self.field_name][0]
            name = f.name
            # Lets see if the field is part of the parent chain. If so we
            # might be able to reuse the already loaded value. Refs #18343.
            val = self._check_parent_chain(instance, name)
            if val is None:
                # We use only() instead of values() here because we want the
                # various data coersion methods (to_python(), etc.) to be
                # called here.
                val = getattr(
                    non_deferred_model._base_manager.only(name).using(
                        instance._state.db).get(pk=instance.pk),
                    self.field_name
                )
            data[self.field_name] = val
        return data[self.field_name] 
Example #24
Source File: manager.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def ensure_default_manager(sender, **kwargs):
    """
    Ensures that a Model subclass contains a default manager  and sets the
    _default_manager attribute on the class. Also sets up the _base_manager
    points to a plain Manager instance (which could be the same as
    _default_manager if it's not a subclass of Manager).
    """
    cls = sender
    if cls._meta.abstract:
        setattr(cls, 'objects', AbstractManagerDescriptor(cls))
        return
    elif cls._meta.swapped:
        setattr(cls, 'objects', SwappedManagerDescriptor(cls))
        return
    if not getattr(cls, '_default_manager', None):
        # Create the default manager, if needed.
        try:
            cls._meta.get_field('objects')
            raise ValueError("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__)
        except FieldDoesNotExist:
            pass
        cls.add_to_class('objects', Manager())
        cls._base_manager = cls.objects
    elif not getattr(cls, '_base_manager', None):
        default_mgr = cls._default_manager.__class__
        if (default_mgr is Manager or
                getattr(default_mgr, "use_for_related_fields", False)):
            cls._base_manager = cls._default_manager
        else:
            # Default manager isn't a plain Manager class, or a suitable
            # replacement, so we walk up the base class hierarchy until we hit
            # something appropriate.
            for base_class in default_mgr.mro()[1:]:
                if (base_class is Manager or
                        getattr(base_class, "use_for_related_fields", False)):
                    cls.add_to_class('_base_manager', base_class())
                    return
            raise AssertionError("Should never get here. Please report a bug, including your model and model manager setup.") 
Example #25
Source File: filters.py    From myblog with GNU Affero General Public License v3.0 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        if len(parts) > 1 and parts[-1] in QUERY_TERMS:
            parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specificially included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field = model._meta.get_field(part)
            except FieldDoesNotExist:
                # Lookups on non-existants fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'rel'):
                model = field.rel.to
                rel_name = field.rel.get_related_field().name
            elif is_related_field(field):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return clean_lookup in self.list_filter 
Example #26
Source File: filters.py    From Mxonline3 with Apache License 2.0 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        # if len(parts) > 1 and parts[-1] in QUERY_TERMS:
        #     parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specificially included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field = model._meta.get_field(part)
            except FieldDoesNotExist:
                # Lookups on non-existants fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'remote_field'):
                model = field.remote_field.to
                rel_name = field.remote_field.get_related_field().name
            elif is_related_field(field):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return clean_lookup in self.list_filter 
Example #27
Source File: filters.py    From CTF_AWD_Platform with MIT License 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        # if len(parts) > 1 and parts[-1] in QUERY_TERMS:
        #     parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specificially included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field = model._meta.get_field(part)
            except FieldDoesNotExist:
                # Lookups on non-existants fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'remote_field'):
                model = field.remote_field.to
                rel_name = field.remote_field.get_related_field().name
            elif is_related_field(field):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return clean_lookup in self.list_filter 
Example #28
Source File: filters.py    From django_OA with GNU General Public License v3.0 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        if len(parts) > 1 and parts[-1] in QUERY_TERMS:
            parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specificially included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field = model._meta.get_field(part)
            except FieldDoesNotExist:
                # Lookups on non-existants fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'rel'):
                model = field.rel.to
                rel_name = field.rel.get_related_field().name
            elif is_related_field(field):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return clean_lookup in self.list_filter 
Example #29
Source File: filters.py    From ImitationTmall_Django with GNU General Public License v3.0 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        if len(parts) > 1 and parts[-1] in QUERY_TERMS:
            parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specificially included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field = model._meta.get_field(part)
            except FieldDoesNotExist:
                # Lookups on non-existants fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'rel'):
                model = field.rel.to
                rel_name = field.rel.get_related_field().name
            elif is_related_field(field):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return clean_lookup in self.list_filter 
Example #30
Source File: filters.py    From weibo-analysis-system with MIT License 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        model = self.model
        # Check FKey lookups that are allowed, so that popups produced by
        # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
        # are allowed to work.
        for l in model._meta.related_fkey_lookups:
            for k, v in widgets.url_params_from_lookup_dict(l).items():
                if k == lookup and v == value:
                    return True

        parts = lookup.split(LOOKUP_SEP)

        # Last term in lookup is a query term (__exact, __startswith etc)
        # This term can be ignored.
        # if len(parts) > 1 and parts[-1] in QUERY_TERMS:
        #     parts.pop()

        # Special case -- foo__id__exact and foo__id queries are implied
        # if foo has been specificially included in the lookup list; so
        # drop __id if it is the last part. However, first we need to find
        # the pk attribute name.
        rel_name = None
        for part in parts[:-1]:
            try:
                field = model._meta.get_field(part)
            except FieldDoesNotExist:
                # Lookups on non-existants fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'remote_field'):
                model = field.remote_field.to
                rel_name = field.remote_field.get_related_field().name
            elif is_related_field(field):
                model = field.model
                rel_name = model._meta.pk.name
            else:
                rel_name = None
        if rel_name and len(parts) > 1 and parts[-1] == rel_name:
            parts.pop()

        if len(parts) == 1:
            return True
        clean_lookup = LOOKUP_SEP.join(parts)
        return clean_lookup in self.list_filter