Python django.db.models 模块,Field() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.Field()

项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def is_required(field: models.Field) -> bool:
        if field.editable is False:
            return False
        if field.auto_created is True:
            return False
        if field.hidden is True:
            return False

        blank = getattr(field, 'blank', None)
        if blank is True:
            return False
        if blank is False:
            return True

        return True

    # noinspection PyUnusedLocal
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def _check_date_hierarchy(self, obj):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if obj.date_hierarchy is None:
            return []
        else:
            try:
                field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
            except (NotRelationField, FieldDoesNotExist):
                return [
                    checks.Error(
                        "The value of 'date_hierarchy' refers to '%s', which "
                        "does not refer to a Field." % obj.date_hierarchy,
                        obj=obj.__class__,
                        id='admin.E127',
                    )
                ]
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
                else:
                    return []
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def _get_declared_fields(cls, bases, attrs):
        fields = [(field_name, attrs.pop(field_name))
                  for field_name, obj in list(attrs.items())
                  if isinstance(obj, Field)]
        fields.sort(key=lambda x: x[1]._creation_counter)

        # If this class is subclassing another Serializer, add that Serializer's
        # fields.  Note that we loop over the bases in *reverse*. This is necessary
        # in order to maintain the correct order of fields.
        for base in reversed(bases):
            if hasattr(base, '_declared_fields'):
                fields = [
                    (field_name, obj) for field_name, obj
                    in base._declared_fields.items()
                    if field_name not in attrs
                ] + fields

        return OrderedDict(fields)
项目:django-cryptography    作者:georgemarshall    | 项目源码 | 文件源码
def get_encrypted_field(base_class):
    """
    A get or create method for encrypted fields, we cache the field in
    the module to avoid recreation. This also allows us to always return
    the same class reference for a field.

    :type base_class: models.Field[T]
    :rtype: models.Field[EncryptedMixin, T]
    """
    assert not isinstance(base_class, models.Field)
    field_name = 'Encrypted' + base_class.__name__
    if base_class not in FIELD_CACHE:
        FIELD_CACHE[base_class] = type(field_name,
                                       (EncryptedMixin, base_class), {
                                           'base_class': base_class,
                                       })
    return FIELD_CACHE[base_class]
项目:django-cryptography    作者:georgemarshall    | 项目源码 | 文件源码
def encrypt(base_field, key=None, ttl=None):
    """
    A decorator for creating encrypted model fields.

    :type base_field: models.Field[T]
    :param bytes key: This is an optional argument.

        Allows for specifying an instance specific encryption key.
    :param int ttl: This is an optional argument.

        The amount of time in seconds that a value can be stored for. If the
        time to live of the data has passed, it will become unreadable.
        The expired value will return an :class:`Expired` object.
    :rtype: models.Field[EncryptedMixin, T]
    """
    if not isinstance(base_field, models.Field):
        assert key is None
        assert ttl is None
        return get_encrypted_field(base_field)

    name, path, args, kwargs = base_field.deconstruct()
    kwargs.update({'key': key, 'ttl': ttl})
    return get_encrypted_field(base_field.__class__)(*args, **kwargs)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def _check_date_hierarchy(self, obj):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if obj.date_hierarchy is None:
            return []
        else:
            try:
                field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
            except (NotRelationField, FieldDoesNotExist):
                return [
                    checks.Error(
                        "The value of 'date_hierarchy' refers to '%s', which "
                        "does not refer to a Field." % obj.date_hierarchy,
                        obj=obj.__class__,
                        id='admin.E127',
                    )
                ]
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
                else:
                    return []
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def _check_date_hierarchy(self, obj):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if obj.date_hierarchy is None:
            return []
        else:
            try:
                field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
            except (NotRelationField, FieldDoesNotExist):
                return [
                    checks.Error(
                        "The value of 'date_hierarchy' refers to '%s', which "
                        "does not refer to a Field." % obj.date_hierarchy,
                        obj=obj.__class__,
                        id='admin.E127',
                    )
                ]
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
                else:
                    return []
项目:django-rtc    作者:scifiswapnil    | 项目源码 | 文件源码
def _check_date_hierarchy(self, obj):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if obj.date_hierarchy is None:
            return []
        else:
            try:
                field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
            except (NotRelationField, FieldDoesNotExist):
                return [
                    checks.Error(
                        "The value of 'date_hierarchy' refers to '%s', which "
                        "does not refer to a Field." % obj.date_hierarchy,
                        obj=obj.__class__,
                        id='admin.E127',
                    )
                ]
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
                else:
                    return []
项目:mes    作者:osess    | 项目源码 | 文件源码
def get_default(self):
        """
        Returns the default value for this field.

        The default implementation on models.Field calls force_unicode
        on the default, which means you can't set arbitrary Python
        objects as the default. To fix this, we just return the value
        without calling force_unicode on it. Note that if you set a
        callable as a default, the field will still call it. It will
        *not* try to pickle and encode it.

        """
        if self.has_default():
            if callable(self.default):
                return self.default()
            return self.default
        # If the field doesn't have a default, then we punt to models.Field.
        return super(PickledObjectField, self).get_default()
项目:mes    作者:osess    | 项目源码 | 文件源码
def get_db_prep_lookup(self, lookup_type, value, connection=None, prepared=False):
        if lookup_type not in ['exact', 'in', 'isnull']:
            raise TypeError('Lookup type %s is not supported.' % lookup_type)
        # The Field model already calls get_db_prep_value before doing the
        # actual lookup, so all we need to do is limit the lookup types.
        try:
            return super(PickledObjectField, self).get_db_prep_lookup(
                lookup_type, value, connection=connection, prepared=prepared)
        except TypeError:
            # Try not to break on older versions of Django, where the
            # `connection` and `prepared` parameters are not available.
            return super(PickledObjectField, self).get_db_prep_lookup(
                lookup_type, value)


# South support; see http://south.aeracode.org/docs/tutorial/part4.html#simple-inheritance
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def _check_date_hierarchy(self, obj):
        """ Check that date_hierarchy refers to DateField or DateTimeField. """

        if obj.date_hierarchy is None:
            return []
        else:
            try:
                field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
            except (NotRelationField, FieldDoesNotExist):
                return [
                    checks.Error(
                        "The value of 'date_hierarchy' refers to '%s', which "
                        "does not refer to a Field." % obj.date_hierarchy,
                        obj=obj.__class__,
                        id='admin.E127',
                    )
                ]
            else:
                if not isinstance(field, (models.DateField, models.DateTimeField)):
                    return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128')
                else:
                    return []
项目:django-postgres-extra    作者:SectorLabs    | 项目源码 | 文件源码
def _is_hstore_field(self, field_name: str) -> Tuple[bool, Optional[models.Field]]:
        """Gets whether the field with the specified name is a
        HStoreField.

        Returns
            A tuple of a boolean indicating whether the field
            with the specified name is a HStoreField, and the
            field instance.
        """

        field_instance = None
        for field in self.model._meta.local_concrete_fields:
            if field.name == field_name or field.column == field_name:
                field_instance = field
                break

        return isinstance(field_instance, HStoreField), field_instance
项目:apimas    作者:grnet    | 项目源码 | 文件源码
def populate_model(model, instances, create=True):
    model_fields = filter((lambda x: isinstance(x, models.Field)),
                          model._meta.get_fields())
    kwargs = {}
    # Outstanding instances in case of Many-to-Many relations.
    outstanding = {}
    for model_field in model_fields:
        if isinstance(model_field, models.AutoField):
            continue
        field_value, isoutstanding = generate_field_value(
            model_field, instances)
        if isoutstanding:
            outstanding[model_field.name] = field_value
        else:
            kwargs[model_field.name] = field_value
    if not create:
        return kwargs
    return create_instance(model, kwargs, outstanding)
项目:apimas    作者:grnet    | 项目源码 | 文件源码
def generate(self, test_models):
        spec = {self.endpoint: {}}
        for model in test_models:
            model_cls = import_object(model)
            collection_name = model_cls.__name__ + '_collection'
            model_fields = filter((lambda x: isinstance(x, models.Field)),
                                  model_cls._meta.get_fields())
            field_schema = self.generate_field_schema(model_fields)
            collection_spec = copy.deepcopy(COLLECTION_TEMPLATE)
            collection_spec['.drf_collection']['model'] = model
            collection_spec['*'] = field_schema
            collection_spec['.actions'] = ACTIONS
            spec[self.endpoint][collection_name] = collection_spec
            spec[self.endpoint].update(
                {'.endpoint': {'permissions': self.permissions}})
        return spec
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def deep_deconstruct(self, obj):
        """
        Recursive deconstruction for a field and its arguments.
        Used for full comparison for rename/alter; sometimes a single-level
        deconstruction will not compare correctly.
        """
        if not hasattr(obj, 'deconstruct') or isinstance(obj, type):
            return obj
        deconstructed = obj.deconstruct()
        if isinstance(obj, models.Field):
            # we have a field which also returns a name
            deconstructed = deconstructed[1:]
        path, args, kwargs = deconstructed
        return (
            path,
            [self.deep_deconstruct(value) for value in args],
            {
                key: self.deep_deconstruct(value)
                for key, value in kwargs.items()
            },
        )
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_NAME_serializer(self, field: models.Field, qs: models.QuerySet, obj=None) -> Serializer:
        """
        Returns serializer <NAME> field. This method (`get_NAME_serializer`) is not supposed to use directly.
        :param obj: optional obj passed to method
        :param field: model field
        :param qs: queryset
        :return: Serializer
        """
        raise Exception()

    # noinspection PyPep8Naming,PyMethodMayBeStatic
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_NAME_queryset(self, field: models.Field, obj=None) -> models.QuerySet:
        """
        Redefines field <NAME> queryset (fk, m2m, etc. querysets).
            This method (`get_NAME_queryset`) is not supposed to use directly.
        :param field:
        :param obj: optional obj passed to method
        :return: QuerySet()
        """
        raise Exception()

    # noinspection PyPep8Naming,PyMethodMayBeStatic
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_NAME_dataset_url(self, field: models.Field, obj=None) -> models.QuerySet:
        """
        Redefines all dataset_url bindings. Supposed to use in runtime
            (when there's no ability to pass reverse_lazy, etc.)
        :param field:
        :param obj: optional obj passed to method
        :return: QuerySet()
        """
        raise Exception()

    # noinspection PyProtectedMember
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def format_choices(field: models.Field):
        for choice in field.choices:
            printable_name = force_text(choice[1])
            yield [choice[0], printable_name]
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def serialize_queryset(self, field: models.Field, qs: models.QuerySet) -> t.Dict:
        serializer = self.get_serializer(field)
        return serializer(qs, many=True).data
项目:drf-metadata    作者:night-crawler    | 项目源码 | 文件源码
def get_field_queryset(self, field: models.Field) -> models.QuerySet:
        custom_queryset_method = getattr(self, 'get_%s_queryset' % field.name.lower(), None)
        if custom_queryset_method is not None:
            return custom_queryset_method(field)

        model = self.get_field_related_model(field.name)
        return model.objects.all()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def deep_deconstruct(self, obj):
        """
        Recursive deconstruction for a field and its arguments.
        Used for full comparison for rename/alter; sometimes a single-level
        deconstruction will not compare correctly.
        """
        if isinstance(obj, list):
            return [self.deep_deconstruct(value) for value in obj]
        elif isinstance(obj, tuple):
            return tuple(self.deep_deconstruct(value) for value in obj)
        elif isinstance(obj, dict):
            return {
                key: self.deep_deconstruct(value)
                for key, value in obj.items()
            }
        elif isinstance(obj, functools.partial):
            return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords))
        elif isinstance(obj, COMPILED_REGEX_TYPE):
            return RegexObject(obj)
        elif isinstance(obj, type):
            # If this is a type that implements 'deconstruct' as an instance method,
            # avoid treating this as being deconstructible itself - see #22951
            return obj
        elif hasattr(obj, 'deconstruct'):
            deconstructed = obj.deconstruct()
            if isinstance(obj, models.Field):
                # we have a field which also returns a name
                deconstructed = deconstructed[1:]
            path, args, kwargs = deconstructed
            return (
                path,
                [self.deep_deconstruct(value) for value in args],
                {
                    key: self.deep_deconstruct(value)
                    for key, value in kwargs.items()
                },
            )
        else:
            return obj
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def from_db_value(self, value, expression, connection, context):
        """Overrides ``models.Field`` method. This converts the value
        returned from the database to an instance of this class.
        """
        return self.to_python(value)
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def to_python(self, value):
        """Overrides ``models.Field`` method. This is used to convert
        bytes (from serialization etc) to an instance of this class"""
        if value is None:
            return None
        elif isinstance(value, oauth2client.client.Credentials):
            return value
        else:
            try:
                return jsonpickle.decode(
                    base64.b64decode(encoding.smart_bytes(value)).decode())
            except ValueError:
                return pickle.loads(
                    base64.b64decode(encoding.smart_bytes(value)))
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def get_prep_value(self, value):
        """Overrides ``models.Field`` method. This is used to convert
        the value from an instances of this class to bytes that can be
        inserted into the database.
        """
        if value is None:
            return None
        else:
            return encoding.smart_text(
                base64.b64encode(jsonpickle.encode(value).encode()))
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def build_unknown_field(self, field_name, model_class):
        """
        Raise an error on any unknown fields.
        """
        raise ImproperlyConfigured(
            'Field name `%s` is not valid for model `%s`.' %
            (field_name, model_class.__name__)
        )
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def from_db_value(self, value, expression, connection, context):
        """Overrides ``models.Field`` method. This converts the value
        returned from the database to an instance of this class.
        """
        return self.to_python(value)
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def to_python(self, value):
        """Overrides ``models.Field`` method. This is used to convert
        bytes (from serialization etc) to an instance of this class"""
        if value is None:
            return None
        elif isinstance(value, oauth2client.client.Credentials):
            return value
        else:
            try:
                return jsonpickle.decode(
                    base64.b64decode(encoding.smart_bytes(value)).decode())
            except ValueError:
                return pickle.loads(
                    base64.b64decode(encoding.smart_bytes(value)))
项目:deb-python-oauth2client    作者:openstack    | 项目源码 | 文件源码
def get_prep_value(self, value):
        """Overrides ``models.Field`` method. This is used to convert
        the value from an instances of this class to bytes that can be
        inserted into the database.
        """
        if value is None:
            return None
        else:
            return encoding.smart_text(
                base64.b64encode(jsonpickle.encode(value).encode()))
项目:django-cryptography    作者:georgemarshall    | 项目源码 | 文件源码
def get_db_prep_value(self, value, connection, prepared=False):
        value = models.Field.get_db_prep_value(self, value, connection,
                                               prepared)
        if value is not None:
            return connection.Database.Binary(self._dump(value))
        return value
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def from_db_value(self, value, expression, connection, context):
        """Overrides ``models.Field`` method. This converts the value
        returned from the database to an instance of this class.
        """
        return self.to_python(value)
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def to_python(self, value):
        """Overrides ``models.Field`` method. This is used to convert
        bytes (from serialization etc) to an instance of this class"""
        if value is None:
            return None
        elif isinstance(value, oauth2client.client.Credentials):
            return value
        else:
            try:
                return jsonpickle.decode(
                    base64.b64decode(encoding.smart_bytes(value)).decode())
            except ValueError:
                return pickle.loads(
                    base64.b64decode(encoding.smart_bytes(value)))
项目:REMAP    作者:REMAPApp    | 项目源码 | 文件源码
def get_prep_value(self, value):
        """Overrides ``models.Field`` method. This is used to convert
        the value from an instances of this class to bytes that can be
        inserted into the database.
        """
        if value is None:
            return None
        else:
            return encoding.smart_text(
                base64.b64encode(jsonpickle.encode(value).encode()))
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def validate_list_filter(self, cls, model):
        """
        Validate that list_filter is a sequence of one of three options:
            1: 'field' - a basic field filter, possibly w/ relationships (eg, 'field__rel')
            2: ('field', SomeFieldListFilter) - a field-based list filter class
            3: SomeListFilter - a non-field list filter class
        """
        from django.contrib.admin import ListFilter, FieldListFilter
        if hasattr(cls, 'list_filter'):
            check_isseq(cls, 'list_filter', cls.list_filter)
            for idx, item in enumerate(cls.list_filter):
                if callable(item) and not isinstance(item, models.Field):
                    # If item is option 3, it should be a ListFilter...
                    if not issubclass(item, ListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                                " which is not a descendant of ListFilter."
                                % (cls.__name__, idx, item.__name__))
                    # ...  but not a FieldListFilter.
                    if issubclass(item, FieldListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                                " which is of type FieldListFilter but is not"
                                " associated with a field name."
                                % (cls.__name__, idx, item.__name__))
                else:
                    if isinstance(item, (tuple, list)):
                        # item is option #2
                        field, list_filter_class = item
                        if not issubclass(list_filter_class, FieldListFilter):
                            raise ImproperlyConfigured("'%s.list_filter[%d][1]'"
                                " is '%s' which is not of type FieldListFilter."
                                % (cls.__name__, idx, list_filter_class.__name__))
                    else:
                        # item is option #1
                        field = item
                    # Validate the field string
                    try:
                        get_fields_from_path(model, field)
                    except (NotRelationField, FieldDoesNotExist):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' refers to '%s'"
                                " which does not refer to a Field."
                                % (cls.__name__, idx, field))
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def _get_declared_fields(cls, bases, attrs):
        fields = [(field_name, attrs.pop(field_name))
                  for field_name, obj in list(attrs.items())
                  if isinstance(obj, Field)]
        fields.sort(key=lambda x: x[1]._creation_counter)

        # If this class is subclassing another Serializer, add that Serializer's
        # fields.  Note that we loop over the bases in *reverse*. This is necessary
        # in order to maintain the correct order of fields.
        for base in reversed(bases):
            if hasattr(base, '_declared_fields'):
                fields = list(base._declared_fields.items()) + fields

        return OrderedDict(fields)
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def build_unknown_field(self, field_name, model_class):
        """
        Raise an error on any unknown fields.
        """
        raise ImproperlyConfigured(
            'Field name `%s` is not valid for model `%s`.' %
            (field_name, model_class.__name__)
        )
项目:wanblog    作者:wanzifa    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
def validate_list_filter(self, cls, model):
        """
        Validate that list_filter is a sequence of one of three options:
            1: 'field' - a basic field filter, possibly w/ relationships (eg, 'field__rel')
            2: ('field', SomeFieldListFilter) - a field-based list filter class
            3: SomeListFilter - a non-field list filter class
        """
        from django.contrib.admin import ListFilter, FieldListFilter
        if hasattr(cls, 'list_filter'):
            check_isseq(cls, 'list_filter', cls.list_filter)
            for idx, item in enumerate(cls.list_filter):
                if callable(item) and not isinstance(item, models.Field):
                    # If item is option 3, it should be a ListFilter...
                    if not issubclass(item, ListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                                " which is not a descendant of ListFilter."
                                % (cls.__name__, idx, item.__name__))
                    # ...  but not a FieldListFilter.
                    if issubclass(item, FieldListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                                " which is of type FieldListFilter but is not"
                                " associated with a field name."
                                % (cls.__name__, idx, item.__name__))
                else:
                    if isinstance(item, (tuple, list)):
                        # item is option #2
                        field, list_filter_class = item
                        if not issubclass(list_filter_class, FieldListFilter):
                            raise ImproperlyConfigured("'%s.list_filter[%d][1]'"
                                " is '%s' which is not of type FieldListFilter."
                                % (cls.__name__, idx, list_filter_class.__name__))
                    else:
                        # item is option #1
                        field = item
                    # Validate the field string
                    try:
                        get_fields_from_path(model, field)
                    except (NotRelationField, FieldDoesNotExist):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' refers to '%s'"
                                " which does not refer to a Field."
                                % (cls.__name__, idx, field))
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
def validate_list_filter(self, cls, model):
        """
        Validate that list_filter is a sequence of one of three options:
            1: 'field' - a basic field filter, possibly w/ relationships (eg, 'field__rel')
            2: ('field', SomeFieldListFilter) - a field-based list filter class
            3: SomeListFilter - a non-field list filter class
        """
        from django.contrib.admin import ListFilter, FieldListFilter
        if hasattr(cls, 'list_filter'):
            check_isseq(cls, 'list_filter', cls.list_filter)
            for idx, item in enumerate(cls.list_filter):
                if callable(item) and not isinstance(item, models.Field):
                    # If item is option 3, it should be a ListFilter...
                    if not issubclass(item, ListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                                " which is not a descendant of ListFilter."
                                % (cls.__name__, idx, item.__name__))
                    # ...  but not a FieldListFilter.
                    if issubclass(item, FieldListFilter):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' is '%s'"
                                " which is of type FieldListFilter but is not"
                                " associated with a field name."
                                % (cls.__name__, idx, item.__name__))
                else:
                    if isinstance(item, (tuple, list)):
                        # item is option #2
                        field, list_filter_class = item
                        if not issubclass(list_filter_class, FieldListFilter):
                            raise ImproperlyConfigured("'%s.list_filter[%d][1]'"
                                " is '%s' which is not of type FieldListFilter."
                                % (cls.__name__, idx, list_filter_class.__name__))
                    else:
                        # item is option #1
                        field = item
                    # Validate the field string
                    try:
                        get_fields_from_path(model, field)
                    except (NotRelationField, FieldDoesNotExist):
                        raise ImproperlyConfigured("'%s.list_filter[%d]' refers to '%s'"
                                " which does not refer to a Field."
                                % (cls.__name__, idx, field))
项目:ims    作者:ims-team    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def deep_deconstruct(self, obj):
        """
        Recursive deconstruction for a field and its arguments.
        Used for full comparison for rename/alter; sometimes a single-level
        deconstruction will not compare correctly.
        """
        if isinstance(obj, list):
            return [self.deep_deconstruct(value) for value in obj]
        elif isinstance(obj, tuple):
            return tuple(self.deep_deconstruct(value) for value in obj)
        elif isinstance(obj, dict):
            return {
                key: self.deep_deconstruct(value)
                for key, value in obj.items()
            }
        elif isinstance(obj, functools.partial):
            return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords))
        elif isinstance(obj, COMPILED_REGEX_TYPE):
            return RegexObject(obj)
        elif isinstance(obj, type):
            # If this is a type that implements 'deconstruct' as an instance method,
            # avoid treating this as being deconstructible itself - see #22951
            return obj
        elif hasattr(obj, 'deconstruct'):
            deconstructed = obj.deconstruct()
            if isinstance(obj, models.Field):
                # we have a field which also returns a name
                deconstructed = deconstructed[1:]
            path, args, kwargs = deconstructed
            return (
                path,
                [self.deep_deconstruct(value) for value in args],
                {
                    key: self.deep_deconstruct(value)
                    for key, value in kwargs.items()
                },
            )
        else:
            return obj
项目:django-open-lecture    作者:DmLitov4    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )
项目:travlr    作者:gauravkulkarni96    | 项目源码 | 文件源码
def test_custom_fields(self):
        self.assertEqual(
            views.get_readable_field_data_type(CustomField()),
            'A custom field type'
        )
        self.assertEqual(
            views.get_readable_field_data_type(DescriptionLackingField()),
            _('Field of type: %(field_type)s') % {
                'field_type': 'DescriptionLackingField'
            }
        )