當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Field方法代碼示例

本文整理匯總了Python中django.db.models.Field方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Field方法的具體用法?Python models.Field怎麽用?Python models.Field使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.db.models的用法示例。


在下文中一共展示了models.Field方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: deep_deconstruct

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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()
            },
        ) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:23,代碼來源:autodetector.py

示例2: get_encrypted_field

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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] 
開發者ID:georgemarshall,項目名稱:django-cryptography,代碼行數:19,代碼來源:fields.py

示例3: encrypt

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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) 
開發者ID:georgemarshall,項目名稱:django-cryptography,代碼行數:25,代碼來源:fields.py

示例4: _check_date_hierarchy

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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 [] 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:24,代碼來源:checks.py

示例5: _get_declared_fields

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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) 
開發者ID:BeanWei,項目名稱:Dailyfresh-B2C,代碼行數:20,代碼來源:serializers.py

示例6: try_dbfield

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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 
開發者ID:BeanWei,項目名稱:Dailyfresh-B2C,代碼行數:20,代碼來源:utils.py

示例7: test_user_specified_details

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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',
            )
        ]) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:22,代碼來源:test_model_field_deprecation.py

示例8: test_db_tablespace

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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'}) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:22,代碼來源:tests.py

示例9: test_user_specified_details

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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',
            )
        ]) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:22,代碼來源:test_model_field_deprecation.py

示例10: test_model_docstring_renders_correctly

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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) 
開發者ID:nesdis,項目名稱:djongo,代碼行數:20,代碼來源:test_views.py

示例11: value_to_string

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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) 
開發者ID:Tautulli,項目名稱:Tautulli,代碼行數:20,代碼來源:models.py

示例12: _is_hstore_field

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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 
開發者ID:SectorLabs,項目名稱:django-postgres-extra,代碼行數:19,代碼來源:sql.py

示例13: _get_field

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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 
開發者ID:rsinger86,項目名稱:drf-flex-fields,代碼行數:8,代碼來源:filter_backends.py

示例14: validate_list_filter

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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)) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:43,代碼來源:validation.py

示例15: test_custom_fields

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Field [as 別名]
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'
            }
        ) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:13,代碼來源:test_fields.py


注:本文中的django.db.models.Field方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。