本文整理汇总了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()
},
)
示例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]
示例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)
示例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 []
示例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)
示例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
示例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',
)
])
示例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'})
示例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',
)
])
示例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)
示例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)
示例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
示例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
示例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))
示例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'
}
)