Python django.db.models.fields.related.ForeignObjectRel() Examples

The following are 29 code examples of django.db.models.fields.related.ForeignObjectRel(). 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.related , or try the search function .
Example #1
Source File: filters.py    From devops with MIT License 6 votes vote down vote up
def choices(self):
        yield {
            'selected': self.lookup_exact_val == '' and not self.lookup_isnull_val,
            'query_string': self.query_string({},
                                              [self.lookup_exact_name, self.lookup_isnull_name]),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_exact_val == smart_unicode(pk_val),
                'query_string': self.query_string({
                    self.lookup_exact_name: pk_val,
                }, [self.lookup_isnull_name]),
                'display': val,
            }
        if (isinstance(self.field, ForeignObjectRel)
                and self.field.field.null or hasattr(self.field, 'rel')
                and self.field.null):
            yield {
                'selected': bool(self.lookup_isnull_val),
                'query_string': self.query_string({
                    self.lookup_isnull_name: 'True',
                }, [self.lookup_exact_name]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #2
Source File: filters.py    From devops with MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        if not (hasattr(field, 'rel') and bool(field.rel) or isinstance(field, ForeignObjectRel)):
            return False
        related_modeladmin = admin_view.admin_site._registry.get(
            get_model_from_relation(field))
        return related_modeladmin and getattr(related_modeladmin, 'relfield_style', None) == 'fk-ajax' 
Example #3
Source File: util.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #4
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_related_m2m(self):
        field_info = self._details(Person, Person._meta.get_field('relating_people'))
        self.assertEqual(field_info[1:], (None, False, True))
        self.assertIsInstance(field_info[0], related.ForeignObjectRel) 
Example #5
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_related_object(self):
        field_info = self._details(Person, Person._meta.get_field('relating_baseperson'))
        self.assertEqual(field_info[1:], (BasePerson, False, False))
        self.assertIsInstance(field_info[0], related.ForeignObjectRel) 
Example #6
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_related_m2m(self):
        field_info = self._details(Person, Person._meta.get_field('relating_people'))
        self.assertEqual(field_info[1:], (None, False, True))
        self.assertIsInstance(field_info[0], related.ForeignObjectRel) 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_related_object(self):
        field_info = self._details(Person, Person._meta.get_field('relating_baseperson'))
        self.assertEqual(field_info[1:], (BasePerson, False, False))
        self.assertIsInstance(field_info[0], related.ForeignObjectRel) 
Example #8
Source File: utils.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def verbose_field_name(model, field_name):
    """
    Get the verbose name for a given ``field_name``. The ``field_name``
    will be traversed across relationships. Returns '[invalid name]' for
    any field name that cannot be traversed.

    ex::

        >>> verbose_field_name(Article, 'author__name')
        'author name'

    """
    if field_name is None:
        return '[invalid name]'

    parts = get_field_parts(model, field_name)
    if not parts:
        return '[invalid name]'

    names = []
    for part in parts:
        if isinstance(part, ForeignObjectRel):
            if part.related_name:
                names.append(part.related_name.replace('_', ' '))
            else:
                return '[invalid name]'
        else:
            names.append(force_text(part.verbose_name))

    return ' '.join(names) 
Example #9
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 #10
Source File: util.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #11
Source File: util.py    From online with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #12
Source File: filters.py    From devops with MIT License 5 votes vote down vote up
def has_output(self):
        if (isinstance(self.field, ForeignObjectRel)
                and self.field.field.null or hasattr(self.field, 'rel')
                and self.field.null):
            extra = 1
        else:
            extra = 0
        return len(self.lookup_choices) + extra > 1 
Example #13
Source File: filters.py    From devops with MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return (hasattr(field, 'rel') and bool(field.rel) or isinstance(field, ForeignObjectRel)) 
Example #14
Source File: util.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #15
Source File: util.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #16
Source File: util.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #17
Source File: schema.py    From djangoql with MIT License 5 votes vote down vote up
def get_field_instance(self, model, field_name):
        field = model._meta.get_field(field_name)
        field_kwargs = {'model': model, 'name': field.name}
        if field.is_relation:
            if not field.related_model:
                # GenericForeignKey
                return
            if self.excluded(field.related_model):
                return
            field_cls = RelationField
            field_kwargs['related_model'] = field.related_model
        else:
            field_cls = self.get_field_cls(field)
        if isinstance(field, (ManyToOneRel, ManyToManyRel, ForeignObjectRel)):
            # Django 1.8 doesn't have .null attribute for these fields
            field_kwargs['nullable'] = True
        else:
            field_kwargs['nullable'] = field.null
        field_kwargs['suggest_options'] = (
            field.name in self.suggest_options.get(model, [])
        )
        return field_cls(**field_kwargs) 
Example #18
Source File: index.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def select_on_queryset(self, queryset):
        """
        This method runs either prefetch_related or select_related on the queryset
        to improve indexing speed of the relation.

        It decides which method to call based on the number of related objects:
         - single (eg ForeignKey, OneToOne), it runs select_related
         - multiple (eg ManyToMany, reverse ForeignKey) it runs prefetch_related
        """
        try:
            field = self.get_field(queryset.model)
        except FieldDoesNotExist:
            return queryset

        if isinstance(field, RelatedField) and not isinstance(field, ParentalManyToManyField):
            if field.many_to_one or field.one_to_one:
                queryset = queryset.select_related(self.field_name)
            elif field.one_to_many or field.many_to_many:
                queryset = queryset.prefetch_related(self.field_name)

        elif isinstance(field, ForeignObjectRel):
            # Reverse relation
            if isinstance(field, OneToOneRel):
                # select_related for reverse OneToOneField
                queryset = queryset.select_related(self.field_name)
            else:
                # prefetch_related for anything else (reverse ForeignKey/ManyToManyField)
                queryset = queryset.prefetch_related(self.field_name)

        return queryset 
Example #19
Source File: index.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_value(self, obj):
        field = self.get_field(obj.__class__)

        if isinstance(field, (RelatedField, ForeignObjectRel)):
            return getattr(obj, self.field_name) 
Example #20
Source File: util.py    From django_OA with GNU General Public License v3.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #21
Source File: util.py    From CTF_AWD_Platform with MIT License 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #22
Source File: util.py    From myblog with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #23
Source File: forms.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, data=None, files=None, instance=None, queryset=None, **kwargs):
        if instance is None:
            self.instance = self.fk.remote_field.model()
        else:
            self.instance = instance

        self.rel_name = ForeignObjectRel(self.fk, self.fk.remote_field.model, related_name=self.fk.remote_field.related_name).get_accessor_name()

        if queryset is None:
            queryset = getattr(self.instance, self.rel_name).all()

        super(BaseChildFormSet, self).__init__(data, files, queryset=queryset, **kwargs) 
Example #24
Source File: util.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def is_related_field(field):
    return isinstance(field, ForeignObjectRel) 
Example #25
Source File: filters.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def choices(self, cl):
        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
        yield {
            'selected': self.lookup_val is None and not self.lookup_val_isnull,
            'query_string': cl.get_query_string({},
                [self.lookup_kwarg, self.lookup_kwarg_isnull]),
            'display': _('All'),
        }
        for pk_val, val in self.lookup_choices:
            yield {
                'selected': self.lookup_val == smart_text(pk_val),
                'query_string': cl.get_query_string({
                    self.lookup_kwarg: pk_val,
                }, [self.lookup_kwarg_isnull]),
                'display': val,
            }
        if (isinstance(self.field, ForeignObjectRel) and
                (self.field.field.null or isinstance(self.field.field, ManyToManyField)) or
                hasattr(self.field, 'rel') and (self.field.null or isinstance(self.field, ManyToManyField))):
            yield {
                'selected': bool(self.lookup_val_isnull),
                'query_string': cl.get_query_string({
                    self.lookup_kwarg_isnull: 'True',
                }, [self.lookup_kwarg]),
                'display': EMPTY_CHANGELIST_VALUE,
            } 
Example #26
Source File: filters.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def has_output(self):
        if (isinstance(self.field, ForeignObjectRel) and
                self.field.field.null or hasattr(self.field, 'rel') and
                self.field.null):
            extra = 1
        else:
            extra = 0
        return len(self.lookup_choices) + extra > 1 
Example #27
Source File: views.py    From wagtailmodeladmin with MIT License 4 votes vote down vote up
def lookup_allowed(self, lookup, value):
        # 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 self.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 specifically 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, _, _, _ = self.model._meta.get_field_by_name(part)
            except FieldDoesNotExist:
                # Lookups on non-existent fields are ok, since they're ignored
                # later.
                return True
            if hasattr(field, 'rel'):
                if field.rel is None:
                    # This property or relation doesn't exist, but it's allowed
                    # since it's ignored in ChangeList.get_filters().
                    return True
                model = field.rel.to
                rel_name = field.rel.get_related_field().name
            elif isinstance(field, ForeignObjectRel):
                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 devops 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 field.is_relation:
                model = field.related_model
                rel_name = field.rel.get_related_field().name
            elif isinstance(field, ForeignObjectRel):
                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: filterset.py    From Dailyfresh-B2C with Apache License 2.0 4 votes vote down vote up
def get_filters(cls):
        """
        Get all filters for the filterset. This is the combination of declared and
        generated filters.
        """

        # No model specified - skip filter generation
        if not cls._meta.model:
            return cls.declared_filters.copy()

        # Determine the filters that should be included on the filterset.
        filters = OrderedDict()
        fields = cls.get_fields()
        undefined = []

        for field_name, lookups in fields.items():
            field = get_model_field(cls._meta.model, field_name)

            # warn if the field doesn't exist.
            if field is None:
                undefined.append(field_name)

            # ForeignObjectRel does not support non-exact lookups
            if isinstance(field, ForeignObjectRel):
                filters[field_name] = cls.filter_for_reverse_field(field, field_name)
                continue

            for lookup_expr in lookups:
                filter_name = cls.get_filter_name(field_name, lookup_expr)

                # If the filter is explicitly declared on the class, skip generation
                if filter_name in cls.declared_filters:
                    filters[filter_name] = cls.declared_filters[filter_name]
                    continue

                if field is not None:
                    filters[filter_name] = cls.filter_for_field(field, field_name, lookup_expr)

        # filter out declared filters
        undefined = [f for f in undefined if f not in cls.declared_filters]
        if undefined:
            raise TypeError(
                "'Meta.fields' contains fields that are not defined on this FilterSet: "
                "%s" % ', '.join(undefined)
            )

        # Add in declared filters. This is necessary since we don't enforce adding
        # declared filters to the 'Meta.fields' option
        filters.update(cls.declared_filters)
        return filters