本文整理汇总了Python中django.contrib.contenttypes.fields.GenericRelation方法的典型用法代码示例。如果您正苦于以下问题:Python fields.GenericRelation方法的具体用法?Python fields.GenericRelation怎么用?Python fields.GenericRelation使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.contrib.contenttypes.fields
的用法示例。
在下文中一共展示了fields.GenericRelation方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: contribute_to_class
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def contribute_to_class(self, cls, name, *args, **kwargs):
@classproperty
def river(_self):
return RiverObject(_self)
self.field_name = name
self._add_to_class(cls, self.field_name + "_transition_approvals",
GenericRelation('%s.%s' % (TransitionApproval._meta.app_label, TransitionApproval._meta.object_name)))
self._add_to_class(cls, self.field_name + "_transitions", GenericRelation('%s.%s' % (Transition._meta.app_label, Transition._meta.object_name)))
if id(cls) not in workflow_registry.workflows:
self._add_to_class(cls, "river", river)
super(StateField, self).contribute_to_class(cls, name, *args, **kwargs)
if id(cls) not in workflow_registry.workflows:
post_save.connect(_on_workflow_object_saved, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
post_delete.connect(_on_workflow_object_deleted, self.model, False, dispatch_uid='%s_%s_riverstatefield_post' % (self.model, name))
workflow_registry.add(self.field_name, cls)
示例2: list_fields
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def list_fields(cls, include_parents=True) -> Generator:
"""
Shortcut to list all field names.
Accepts parameter `include_parents=False` with which returnes only fields defined in current model.
This behaviour is little different from django's — its _meta.get_fields(include_parents=False) returns
fields taken from inherited models, and we do not
"""
if include_parents:
return (field.name for field in cls._meta.get_fields(include_parents=True) if not isinstance(field, GenericRelation))
else:
parent_fields = set()
for parent in inspect.getmro(cls):
if issubclass(parent, models.Model) and hasattr(parent, '_meta'): # if it is a django model
if not issubclass(parent, cls): # ignore the lowest model in tree
for field in parent._meta.get_fields(include_parents=False):
if not isinstance(field, GenericRelation):
parent_fields.update([field.name])
return (field.name for field in cls._meta.get_fields(include_parents=False) if field.name not in parent_fields)
示例3: _register_model
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def _register_model(admin, model):
if not hasattr(admin, 'reversion_format'):
admin.reversion_format = 'json'
if not is_registered(model):
inline_fields = []
for inline in getattr(admin, 'inlines', []):
inline_model = inline.model
if getattr(inline, 'generic_inline', False):
ct_field = getattr(inline, 'ct_field', 'content_type')
ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
for field in model._meta.many_to_many:
if isinstance(field, GenericRelation) \
and field.rel.to == inline_model \
and field.object_id_field_name == ct_fk_field \
and field.content_type_field_name == ct_field:
inline_fields.append(field.name)
_autoregister(admin, inline_model)
else:
fk_name = getattr(inline, 'fk_name', None)
if not fk_name:
for field in inline_model._meta.fields:
if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to):
fk_name = field.name
_autoregister(admin, inline_model, follow=[fk_name])
if not inline_model._meta.get_field(fk_name).rel.is_hidden():
accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
inline_fields.append(accessor)
_autoregister(admin, model, inline_fields)
示例4: _register_model
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def _register_model(admin, model):
if not hasattr(admin, 'reversion_format'):
admin.reversion_format = 'json'
if not is_registered(model):
inline_fields = []
for inline in getattr(admin, 'inlines', []):
inline_model = inline.model
if getattr(inline, 'generic_inline', False):
ct_field = getattr(inline, 'ct_field', 'content_type')
ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id')
for field in model._meta.many_to_many:
if isinstance(field, GenericRelation) \
and field.rel.to == inline_model \
and field.object_id_field_name == ct_fk_field \
and field.content_type_field_name == ct_field:
inline_fields.append(field.name)
_autoregister(admin, inline_model)
else:
fk_name = getattr(inline, 'fk_name', None)
if not fk_name:
for field in inline_model._meta.fields:
if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.remote_field.model):
fk_name = field.name
_autoregister(admin, inline_model, follow=[fk_name])
if not inline_model._meta.get_field(fk_name).remote_field.is_hidden():
accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name()
inline_fields.append(accessor)
_autoregister(admin, model, inline_fields)
示例5: generate_model_from_entity
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def generate_model_from_entity(entity):
def to_string(self):
return self.name
model_attrs = {
'__module__': __name__,
'model_name': entity.name,
'name': models.CharField(max_length=100, blank=True),
'x': models.FloatField(default=0),
'y': models.FloatField(default=0),
'z': models.FloatField(default=0),
'length': models.FloatField(default=0),
'width': models.FloatField(default=0),
'height': models.FloatField(default=0),
'model': models.ForeignKey(Model3D, null=True, related_name='+'),
'parent': ParentField(entity.name),
'resources': GenericRelation(
Resource, object_id_field='location_id',
content_type_field='location_type'
),
'__str__': to_string,
'__doc__': entity.description
}
return type(entity.name, (models.Model,), model_attrs)
# A dictionary of all of the classes in the layout tree that have been created
# so we can be sure not to create a class that has already been created
示例6: _handle_o2m_related_field
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def _handle_o2m_related_field(self, related_field: Field, alias_object: Model):
if isinstance(related_field, GenericRelation):
fields = related_field.remote_field.model._meta.private_fields
matching_field = [f for f in fields if related_field._is_matching_generic_foreign_key(f)][0]
reverse_o2m_accessor_name = related_field.get_attname()
o2m_accessor_name = matching_field.name
else:
reverse_o2m_accessor_name = related_field.get_accessor_name()
o2m_accessor_name = related_field.field.name
for obj in getattr(alias_object, reverse_o2m_accessor_name).all():
try:
logger.debug(f'Attempting to set o2m field {o2m_accessor_name} on '
f'{obj._meta.model.__name__}[pk={obj.pk}] to '
f'{self.model_meta.model_name}[pk={self.primary_object.pk}] ...')
setattr(obj, o2m_accessor_name, self.primary_object)
obj.validate_unique()
obj.save()
logger.debug('success.')
except ValidationError as e:
logger.debug(f'failed. {e}')
if self.raise_validation_exception:
raise
if related_field.field.null:
logger.debug(f'Setting o2m field {o2m_accessor_name} on '
f'{obj._meta.model.__name__}[pk={obj.pk}] to `None`')
setattr(obj, o2m_accessor_name, None)
obj.save()
else:
logger.debug(f'Deleting {obj._meta.model.__name__}[pk={obj.pk}]')
_pk = obj.pk
obj.delete()
obj.pk = _pk # pk is cached and re-assigned to keep the audit trail in tact
self.modified_related_objects.append(obj)
示例7: create_link
# 需要导入模块: from django.contrib.contenttypes import fields [as 别名]
# 或者: from django.contrib.contenttypes.fields import GenericRelation [as 别名]
def create_link(linkable_model, linked_model, linkable_link_name=None, verbose_name=None, verbose_name_plural=None):
class LinkedModel(object):
def __init__(self, model, link_name=None, verbose_name=None, verbose_name_plural=None, reverse_link_name=None):
self.model = model
self.link_name = link_name
self.reverse_link_name = reverse_link_name
self.verbose_name = verbose_name
self.verbose_name_plural = verbose_name_plural
if issubclass(linkable_model, ManyLinkableModel):
get_link_name = get_plural
elif issubclass(linkable_model, OneLinkableModel):
get_link_name = get_singular
if linkable_link_name is None:
linkable_link_name = get_link_name(linked_model)
if verbose_name is None:
verbose_name = linked_model._meta.verbose_name
if verbose_name_plural is None:
verbose_name_plural = linked_model._meta.verbose_name_plural
linked_link_name = get_plural(linkable_model)
if issubclass(linkable_model, ManyLinkableModel):
field = models.ManyToManyField(linkable_model, related_name=linkable_link_name)
setattr(linked_model, linked_link_name, field)
field.contribute_to_class(linked_model, linked_link_name)
elif issubclass(linkable_model, OneLinkableModel):
linked_link_name = get_singular(linkable_model)+"_set"
field = GenericRelation(linkable_model, related_query_name=linkable_link_name)
setattr(linked_model, linked_link_name, field)
field.contribute_to_class(linked_model, linked_link_name)
setattr(linkable_model, linkable_link_name, property(
fget=lambda x: linkable_model.get_related(x),
fset=lambda x, y: linkable_model.set_related(x, y)))
if not hasattr(linkable_model, "_LINKS") or linkable_model._LINKS is None:
setattr(linkable_model, "_LINKS", dict())
linkable_model._LINKS[linkable_link_name] = LinkedModel(
linked_model, link_name=linkable_link_name,
verbose_name=verbose_name,
verbose_name_plural=verbose_name_plural,
reverse_link_name=linked_link_name)
return linkable_model