Python django.db.models.Field() Examples

The following are 30 code examples for showing how to use django.db.models.Field(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: autodetector.py    License: GNU General Public License v2.0 6 votes vote down vote up
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()
            },
        ) 
Example 2
Project: django-cryptography   Author: georgemarshall   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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] 
Example 3
Project: django-cryptography   Author: georgemarshall   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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(type(base_field))(*args, **kwargs) 
Example 4
Project: bioforum   Author: reBiocoder   File: checks.py    License: MIT License 6 votes vote down vote up
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 [] 
Example 5
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: checks.py    License: MIT License 6 votes vote down vote up
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 [] 
Example 6
Project: python   Author: Yeah-Kun   File: checks.py    License: Apache License 2.0 6 votes vote down vote up
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 [] 
Example 7
Project: python2017   Author: bpgc-cte   File: checks.py    License: MIT License 6 votes vote down vote up
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 [] 
Example 8
Project: Dailyfresh-B2C   Author: BeanWei   File: serializers.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 9
Project: Dailyfresh-B2C   Author: BeanWei   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def try_dbfield(fn, field_class):
    """
    Try ``fn`` with the DB ``field_class`` by walking its
    MRO until a result is found.

    ex::
        _try_dbfield(field_dict.get, models.CharField)

    """
    # walk the mro, as field_class could be a derived model field.
    for cls in field_class.mro():
        # skip if cls is models.Field
        if cls is models.Field:
            continue

        data = fn(cls)
        if data:
            return data 
Example 10
def test_user_specified_details(self):
        class MyField(models.Field):
            system_check_deprecated_details = {
                'msg': 'This field is deprecated and will be removed soon.',
                'hint': 'Use something else.',
                'id': 'fields.W999',
            }

        class Model(models.Model):
            name = MyField()

        model = Model()
        self.assertEqual(model.check(), [
            checks.Warning(
                msg='This field is deprecated and will be removed soon.',
                hint='Use something else.',
                obj=Model._meta.get_field('name'),
                id='fields.W999',
            )
        ]) 
Example 11
def test_user_specified_details(self):
        class MyField(models.Field):
            system_check_removed_details = {
                'msg': 'Support for this field is gone.',
                'hint': 'Use something else.',
                'id': 'fields.E999',
            }

        class Model(models.Model):
            name = MyField()

        model = Model()
        self.assertEqual(model.check(), [
            checks.Error(
                msg='Support for this field is gone.',
                hint='Use something else.',
                obj=Model._meta.get_field('name'),
                id='fields.E999',
            )
        ]) 
Example 12
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_db_tablespace(self):
        field = models.Field()
        _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})
        # With a DEFAULT_DB_TABLESPACE.
        with self.settings(DEFAULT_DB_TABLESPACE='foo'):
            _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})
        # With a db_tablespace.
        field = models.Field(db_tablespace='foo')
        _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'db_tablespace': 'foo'})
        # With a db_tablespace equal to DEFAULT_DB_TABLESPACE.
        with self.settings(DEFAULT_DB_TABLESPACE='foo'):
            _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'db_tablespace': 'foo'}) 
Example 13
def test_user_specified_details(self):
        class MyField(models.Field):
            system_check_removed_details = {
                'msg': 'Support for this field is gone.',
                'hint': 'Use something else.',
                'id': 'fields.E999',
            }

        class Model(models.Model):
            name = MyField()

        model = Model()
        self.assertEqual(model.check(), [
            checks.Error(
                msg='Support for this field is gone.',
                hint='Use something else.',
                obj=Model._meta.get_field('name'),
                id='fields.E999',
            )
        ]) 
Example 14
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_db_tablespace(self):
        field = models.Field()
        _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})
        # With a DEFAULT_DB_TABLESPACE.
        with self.settings(DEFAULT_DB_TABLESPACE='foo'):
            _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {})
        # With a db_tablespace.
        field = models.Field(db_tablespace='foo')
        _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'db_tablespace': 'foo'})
        # With a db_tablespace equal to DEFAULT_DB_TABLESPACE.
        with self.settings(DEFAULT_DB_TABLESPACE='foo'):
            _, _, args, kwargs = field.deconstruct()
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {'db_tablespace': 'foo'}) 
Example 15
Project: djongo   Author: nesdis   File: test_views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_model_docstring_renders_correctly(self):
        summary = (
            '<h2 class="subhead"><p>Stores information about a person, related to <a class="reference external" '
            'href="/admindocs/models/myapp.company/">myapp.Company</a>.</p></h2>'
        )
        subheading = '<p><strong>Notes</strong></p>'
        body = '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this object.</p>'
        model_body = (
            '<dl class="docutils"><dt><tt class="'
            'docutils literal">company</tt></dt><dd>Field storing <a class="'
            'reference external" href="/admindocs/models/myapp.company/">'
            'myapp.Company</a> where the person works.</dd></dl>'
        )
        self.assertContains(self.response, 'DESCRIPTION')
        self.assertContains(self.response, summary, html=True)
        self.assertContains(self.response, subheading, html=True)
        self.assertContains(self.response, body, html=True)
        self.assertContains(self.response, model_body, html=True) 
Example 16
Project: Tautulli   Author: Tautulli   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def value_to_string(self, obj):
        """
        We need to support both legacy `_get_val_from_obj` and new `value_from_object` models.Field methods.
        It would be better to wrap it with try -> except AttributeError -> fallback to legacy.
        Unfortunately, we can catch AttributeError exception from `value_from_object` function itself.
        Parsing exception string is an overkill here, that's why we check for attribute existence

        :param obj: Value to serialize

        :return: Serialized value
        """

        if hasattr(self, 'value_from_object'):
            value = self.value_from_object(obj)
        else:  # fallback for legacy django versions
            value = self._get_val_from_obj(obj)

        return self.get_prep_value(value) 
Example 17
Project: django-postgres-extra   Author: SectorLabs   File: sql.py    License: MIT License 6 votes vote down vote up
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 
Example 18
Project: drf-flex-fields   Author: rsinger86   File: filter_backends.py    License: MIT License 5 votes vote down vote up
def _get_field(field_name: str, model: models.Model) -> Optional[models.Field]:
        try:
            # noinspection PyProtectedMember
            return model._meta.get_field(field_name)
        except models.FieldDoesNotExist:
            return None 
Example 19
Project: GTDWeb   Author: lanbing510   File: validation.py    License: GNU General Public License v2.0 5 votes vote down vote up
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)) 
Example 20
Project: GTDWeb   Author: lanbing510   File: test_fields.py    License: GNU General Public License v2.0 5 votes vote down vote up
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'
            }
        ) 
Example 21
Project: django-cryptography   Author: georgemarshall   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example 22
def pre_sql_setup(self, fields, obj):
        """ Based on the model supplied, build a database value prep_map for fields
            This dict of lambdas will apply model database prep conversions as per
             Django norm.
            As literal sets are simplistic, this can be generated once instead of
             checking per object.
        """

        # Determine appropriate mapping set
        if isinstance(obj, dict):
            self.get_value = self.value_lambdas["dict"]
        elif hasattr(obj, "_fields") or all((hasattr(obj, field) for field in fields)):
            self.get_value = self.value_lambdas["attr"]
        else:
            self.get_value = self.value_lambdas["list"]

        if all(isinstance(field, Field) for field in fields):
            self.prep_mapping = OrderedDict()
            # Create type savvy field conversion list
            for field in fields:
                if not field.is_relation:
                    self.prep_mapping[field] = self.field_lambdas["val"]
                elif field.is_relation and field.name.endswith("_id"):
                    self.prep_mapping[field] = self.field_lambdas["key"]
                elif field.is_relation:
                    self.prep_mapping[field] = self.field_lambdas["rel"]
            # Promote more complex conversion iter
            self.obj_values = self.obj_values_prepped 
Example 23
Project: bioforum   Author: reBiocoder   File: autodetector.py    License: MIT License 5 votes vote down vote up
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 
Example 24
Project: karrot-backend   Author: yunity   File: base_models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_explicit_field_names(self):
        """
        :rtype: list
        """
        return [
            field.name for field in self._meta.get_fields()
            if isinstance(field, Field) and not isinstance(field, RelatedField)
        ] 
Example 25
Project: aqua-monitor   Author: Deltares   File: models.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 26
Project: aqua-monitor   Author: Deltares   File: models.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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))) 
Example 27
Project: aqua-monitor   Author: Deltares   File: models.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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())) 
Example 28
Project: online-judge   Author: DMOJ   File: raw_sql.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def RawSQLColumn(model, field=None):
    if isinstance(model, Field):
        field = model
        model = field.model
    if isinstance(field, six.string_types):
        field = model._meta.get_field(field)
    return RawSQL('%s.%s' % (model._meta.db_table, field.get_attname_column()[1]), ()) 
Example 29
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: autodetector.py    License: MIT License 5 votes vote down vote up
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 
Example 30
Project: wagtail   Author: wagtail   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __get__(self, obj, type=None):
        if obj is None:
            return self
        field_name = self.field.name

        if field_name not in obj.__dict__:
            # Field is deferred. Fetch it from db.
            obj.refresh_from_db(fields=[field_name])
        return obj.__dict__[field_name]