本文整理汇总了Python中django.db.models.fields.related.RelatedField方法的典型用法代码示例。如果您正苦于以下问题:Python related.RelatedField方法的具体用法?Python related.RelatedField怎么用?Python related.RelatedField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.fields.related
的用法示例。
在下文中一共展示了related.RelatedField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: invalidate_model_cache
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def invalidate_model_cache(self):
"""
Invalidate model cache by generating new key for the model.
"""
logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table))
if django.VERSION >= (1, 8):
related_tables = set(
[f.related_model._meta.db_table for f in self.model._meta.get_fields()
if ((f.one_to_many or f.one_to_one) and f.auto_created)
or f.many_to_one or (f.many_to_many and not f.auto_created)])
else:
related_tables = set([rel.model._meta.db_table for rel in self.model._meta.get_all_related_objects()])
# temporary fix for m2m relations with an intermediate model, goes away after better join caching
related_tables |= set([field.rel.to._meta.db_table for field in self.model._meta.fields if issubclass(type(field), RelatedField)])
logger.debug('Related tables of model {0} are {1}'.format(self.model, related_tables))
update_model_cache(self.model._meta.db_table)
for related_table in related_tables:
update_model_cache(related_table)
示例2: field_map
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def field_map(path, field_class_path):
"""
Maps paths to a lambda that converts a value of that path
to a human readable type. Dates are formatted and
related objects called object.label
:param path: The simple or concatinated path to a field
:param field_class_path: A string representation of the field class
"""
resolved_field_class = resolve_module_attr(field_class_path)
if issubclass(resolved_field_class, DateField):
# Convert to localtime (tzinfo for client will need to be specified in settings or passed from client)
# We need to convert the timezone offset from [-]HHMM to [-]HH:MM to match javascript's format
return [path, lambda date: date and re.sub(
r'(\d{2})(\d{2})$',
r'\1:\2',
date.astimezone(tzlocal()).strftime("%Y-%m-%dT%H:%M:%S%z"))
]
if issubclass(resolved_field_class, RelatedField):
# Insist that the related instances have a label property to present to
# the user. Use the string format as a last resort
return [path, FeatureFieldMixin.resolve_instance_label]
return None
示例3: get_type
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_type(self, cls):
if 'type' in self.kwargs:
return self.kwargs['type']
try:
field = self.get_field(cls)
# Follow foreign keys to find underlying type
# We use a while loop as it's possible for a foreign key
# to target a foreign key in another model.
# (for example, a foreign key to a child page model will
# point to the `page_ptr_id` field so we need to follow this
# second foreign key to find the `id`` field in the Page model)
while isinstance(field, RelatedField):
field = field.target_field
return field.get_internal_type()
except FieldDoesNotExist:
return 'CharField'
示例4: get_field_type_from_lookup
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_field_type_from_lookup(ctx: MethodContext, django_context: DjangoContext, model_cls: Type[Model],
*, method: str, lookup: str) -> Optional[MypyType]:
try:
lookup_field = django_context.resolve_lookup_into_field(model_cls, lookup)
except FieldError as exc:
ctx.api.fail(exc.args[0], ctx.context)
return None
except LookupsAreUnsupported:
return AnyType(TypeOfAny.explicit)
if ((isinstance(lookup_field, RelatedField) and lookup_field.column == lookup)
or isinstance(lookup_field, ForeignObjectRel)):
related_model_cls = django_context.get_field_related_model_cls(lookup_field)
if related_model_cls is None:
return AnyType(TypeOfAny.from_error)
lookup_field = django_context.get_primary_key_field(related_model_cls)
field_get_type = django_context.get_field_get_type(helpers.get_typechecker_api(ctx),
lookup_field, method=method)
return field_get_type
示例5: get_field_lookup_exact_type
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_field_lookup_exact_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel]) -> MypyType:
if isinstance(field, (RelatedField, ForeignObjectRel)):
related_model_cls = field.related_model
primary_key_field = self.get_primary_key_field(related_model_cls)
primary_key_type = self.get_field_get_type(api, primary_key_field, method='init')
rel_model_info = helpers.lookup_class_typeinfo(api, related_model_cls)
if rel_model_info is None:
return AnyType(TypeOfAny.explicit)
model_and_primary_key_type = UnionType.make_union([Instance(rel_model_info, []), primary_key_type])
return helpers.make_optional(model_and_primary_key_type)
field_info = helpers.lookup_class_typeinfo(api, field.__class__)
if field_info is None:
return AnyType(TypeOfAny.explicit)
return helpers.get_private_descriptor_type(field_info, '_pyi_lookup_exact_type',
is_nullable=field.null)
示例6: get_field_get_type
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_field_get_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType:
""" Get a type of __get__ for this specific Django field. """
field_info = helpers.lookup_class_typeinfo(api, field.__class__)
if field_info is None:
return AnyType(TypeOfAny.unannotated)
is_nullable = self.get_field_nullability(field, method)
if isinstance(field, RelatedField):
related_model_cls = self.get_field_related_model_cls(field)
if related_model_cls is None:
return AnyType(TypeOfAny.from_error)
if method == 'values':
primary_key_field = self.get_primary_key_field(related_model_cls)
return self.get_field_get_type(api, primary_key_field, method=method)
model_info = helpers.lookup_class_typeinfo(api, related_model_cls)
if model_info is None:
return AnyType(TypeOfAny.unannotated)
return Instance(model_info, [])
else:
return helpers.get_private_descriptor_type(field_info, '_pyi_private_get_type',
is_nullable=is_nullable)
示例7: get_field_related_model_cls
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_field_related_model_cls(self, field: Union[RelatedField, ForeignObjectRel]) -> Optional[Type[Model]]:
if isinstance(field, RelatedField):
related_model_cls = field.remote_field.model
else:
related_model_cls = field.field.model
if isinstance(related_model_cls, str):
if related_model_cls == 'self':
# same model
related_model_cls = field.model
elif '.' not in related_model_cls:
# same file model
related_model_fullname = field.model.__module__ + '.' + related_model_cls
related_model_cls = self.get_model_class_by_fullname(related_model_fullname)
else:
related_model_cls = self.apps_registry.get_model(related_model_cls)
return related_model_cls
示例8: get_dependencies
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_dependencies(self):
# Generate the default dependencies for a related field
dependencies = super(DjangoRelatedField, self).get_dependencies()
if self.remote_field:
# Account for FKs to swappable models
swappable_setting = getattr(self, 'swappable_setting', None)
if swappable_setting is not None:
dep_app_label = "__setting__"
dep_object_name = swappable_setting
else:
dep_app_label = self.remote_field.model._meta.app_label
dep_object_name = self.remote_field.model._meta.object_name
# Depend on the model that this refers to
dependencies.append(dependency_tuple(
app_label=dep_app_label,
object_name=dep_object_name,
field=None,
created=True))
# And any manually declared through model
if getattr(self.remote_field, 'through', None) and not self.remote_field.through._meta.auto_created:
dependencies.append(dependency_tuple(
app_label=self.remote_field.through._meta.app_label,
object_name=self.remote_field.through._meta.object_name,
field=None,
created=True))
return dependencies
# Make fields able to declare arbitrary dependencies
示例9: _get_explicit_field_names
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
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)
]
示例10: invalidate_model_cache
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def invalidate_model_cache(sender, instance, **kwargs):
"""
Signal receiver for models to invalidate model cache of sender and related models.
Model cache is invalidated by generating new key for each model.
Parameters
~~~~~~~~~~
sender
The model class
instance
The actual instance being saved.
"""
logger.debug('Received post_save/post_delete signal from sender {0}'.format(sender))
if django.VERSION >= (1, 8):
related_tables = set(
[f.related_model._meta.db_table for f in sender._meta.get_fields()
if f.related_model is not None
and (((f.one_to_many or f.one_to_one) and f.auto_created)
or f.many_to_one or (f.many_to_many and not f.auto_created))])
else:
related_tables = set([rel.model._meta.db_table for rel in sender._meta.get_all_related_objects()])
# temporary fix for m2m relations with an intermediate model, goes away after better join caching
related_tables |= set([field.rel.to._meta.db_table for field in sender._meta.fields if issubclass(type(field), RelatedField)])
logger.debug('Related tables of sender {0} are {1}'.format(sender, related_tables))
update_model_cache(sender._meta.db_table)
for related_table in related_tables:
update_model_cache(related_table)
示例11: get_value
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_value(self, obj):
from taggit.managers import TaggableManager
try:
field = self.get_field(obj.__class__)
value = field.value_from_object(obj)
if hasattr(field, 'get_searchable_content'):
value = field.get_searchable_content(value)
elif isinstance(field, TaggableManager):
# As of django-taggit 1.0, value_from_object returns a list of Tag objects,
# which matches what we want
pass
elif isinstance(field, RelatedField):
# The type of the ForeignKey may have a get_searchable_content method that we should
# call. Firstly we need to find the field its referencing but it may be referencing
# another RelatedField (eg an FK to page_ptr_id) so we need to run this in a while
# loop to find the actual remote field.
remote_field = field
while isinstance(remote_field, RelatedField):
remote_field = remote_field.target_field
if hasattr(remote_field, 'get_searchable_content'):
value = remote_field.get_searchable_content(value)
return value
except FieldDoesNotExist:
value = getattr(obj, self.field_name, None)
if hasattr(value, '__call__'):
value = value()
return value
示例12: select_on_queryset
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def select_on_queryset(self, queryset):
"""
This method runs either prefetch_related or select_related on the queryset
to improve indexing speed of the relation.
It decides which method to call based on the number of related objects:
- single (eg ForeignKey, OneToOne), it runs select_related
- multiple (eg ManyToMany, reverse ForeignKey) it runs prefetch_related
"""
try:
field = self.get_field(queryset.model)
except FieldDoesNotExist:
return queryset
if isinstance(field, RelatedField) and not isinstance(field, ParentalManyToManyField):
if field.many_to_one or field.one_to_one:
queryset = queryset.select_related(self.field_name)
elif field.one_to_many or field.many_to_many:
queryset = queryset.prefetch_related(self.field_name)
elif isinstance(field, ForeignObjectRel):
# Reverse relation
if isinstance(field, OneToOneRel):
# select_related for reverse OneToOneField
queryset = queryset.select_related(self.field_name)
else:
# prefetch_related for anything else (reverse ForeignKey/ManyToManyField)
queryset = queryset.prefetch_related(self.field_name)
return queryset
示例13: contains_plural_field
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def contains_plural_field(model, fields):
""" Returns a boolean indicating if ``fields`` contains a relationship to multiple items. """
source_model = model
for orm_path in fields:
model = source_model
bits = orm_path.lstrip('+-').split('__')
for bit in bits[:-1]:
field, _ = get_field(model._meta, bit)
if isinstance(field, models.ManyToManyField) \
or (USE_RELATED_OBJECT and isinstance(field, RelatedObject) and field.field.rel.multiple) \
or (not USE_RELATED_OBJECT and isinstance(field, RelatedField) and field.one_to_many):
return True
model = get_model_at_related_field(model, bit)
return False
示例14: get_field_parts
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_field_parts(model, field_name):
"""
Get the field parts that represent the traversable relationships from the
base ``model`` to the final field, described by ``field_name``.
ex::
>>> parts = get_field_parts(Book, 'author__first_name')
>>> [p.verbose_name for p in parts]
['author', 'first name']
"""
parts = field_name.split(LOOKUP_SEP)
opts = model._meta
fields = []
# walk relationships
for name in parts:
try:
field = opts.get_field(name)
except FieldDoesNotExist:
return None
fields.append(field)
if isinstance(field, RelatedField):
opts = remote_model(field)._meta
elif isinstance(field, ForeignObjectRel):
opts = field.related_model._meta
return fields
示例15: get_field_lookup_exact_type
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import RelatedField [as 别名]
def get_field_lookup_exact_type(api: TypeChecker, field: Field) -> MypyType:
if isinstance(field, (RelatedField, ForeignObjectRel)):
lookup_type_class = field.related_model
rel_model_info = lookup_class_typeinfo(api, lookup_type_class)
if rel_model_info is None:
return AnyType(TypeOfAny.from_error)
return make_optional(Instance(rel_model_info, []))
field_info = lookup_class_typeinfo(api, field.__class__)
if field_info is None:
return AnyType(TypeOfAny.explicit)
return get_private_descriptor_type(field_info, '_pyi_lookup_exact_type',
is_nullable=field.null)