本文整理汇总了Python中django.db.models.fields.related.ManyToManyField方法的典型用法代码示例。如果您正苦于以下问题:Python related.ManyToManyField方法的具体用法?Python related.ManyToManyField怎么用?Python related.ManyToManyField使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models.fields.related
的用法示例。
在下文中一共展示了related.ManyToManyField方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_all_related_objects
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def get_all_related_objects(self, local_only=False, include_hidden=False,
include_proxy_eq=False):
include_parents = True if local_only is False else PROXY_PARENTS
fields = self._get_fields(
forward=False, reverse=True,
include_parents=include_parents,
include_hidden=include_hidden,
)
fields = (obj for obj in fields if not isinstance(obj.field, ManyToManyField))
if include_proxy_eq:
children = chain.from_iterable(c._relation_tree
for c in self.concrete_model._meta.proxied_children
if c is not self)
relations = (f.rel for f in children
if include_hidden or not f.rel.field.rel.is_hidden())
fields = chain(fields, relations)
return list(fields)
示例2: get_all_related_objects
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def get_all_related_objects(self, local_only=False, include_hidden=False,
include_proxy_eq=False):
include_parents = True if local_only is False else PROXY_PARENTS
fields = self._get_fields(
forward=False, reverse=True,
include_parents=include_parents,
include_hidden=include_hidden,
)
fields = (obj for obj in fields if not isinstance(obj.field, ManyToManyField))
if include_proxy_eq:
children = chain.from_iterable(c._relation_tree
for c in self.concrete_model._meta.proxied_children
if c is not self)
relations = (f.remote_field for f in children
if include_hidden or not f.remote_field.field.remote_field.is_hidden())
fields = chain(fields, relations)
return list(fields)
示例3: model_to_dict
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def model_to_dict(instance, fields=None, exclude=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument.
"""
# avoid a circular import
from django.db.models.fields.related import ManyToManyField
opts = instance._meta
data = {}
for f in chain(opts.concrete_fields, opts.virtual_fields, opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fields and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
if isinstance(f, ManyToManyField):
# If the object doesn't have a primary key yet, just use an empty
# list for its m2m fields. Calling f.value_from_object will raise
# an exception.
if instance.pk is None:
data[f.name] = []
else:
# MultipleChoiceWidget needs a list of pks, not object instances.
qs = f.value_from_object(instance)
if qs._result_cache is not None:
data[f.name] = [item.pk for item in qs]
else:
data[f.name] = list(qs.values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data
示例4: get_all_related_many_to_many_objects
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def get_all_related_many_to_many_objects(self, local_only=False):
include_parents = True if local_only is not True else PROXY_PARENTS
fields = self._get_fields(
forward=False, reverse=True,
include_parents=include_parents, include_hidden=True
)
return [obj for obj in fields if isinstance(obj.field, ManyToManyField)]
示例5: get_all_related_m2m_objects_with_model
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def get_all_related_m2m_objects_with_model(self):
fields = self._get_fields(forward=False, reverse=True, include_hidden=True)
return [self._map_model(obj) for obj in fields if isinstance(obj.field, ManyToManyField)]
示例6: choices
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def choices(self, cl):
from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
yield {
'selected': self.lookup_val is None and not self.lookup_val_isnull,
'query_string': cl.get_query_string({},
[self.lookup_kwarg, self.lookup_kwarg_isnull]),
'display': _('All'),
}
for pk_val, val in self.lookup_choices:
yield {
'selected': self.lookup_val == smart_text(pk_val),
'query_string': cl.get_query_string({
self.lookup_kwarg: pk_val,
}, [self.lookup_kwarg_isnull]),
'display': val,
}
if (isinstance(self.field, ForeignObjectRel) and
(self.field.field.null or isinstance(self.field.field, ManyToManyField)) or
hasattr(self.field, 'rel') and (self.field.null or isinstance(self.field, ManyToManyField))):
yield {
'selected': bool(self.lookup_val_isnull),
'query_string': cl.get_query_string({
self.lookup_kwarg_isnull: 'True',
}, [self.lookup_kwarg]),
'display': EMPTY_CHANGELIST_VALUE,
}
示例7: to_dict
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def to_dict(self):
data = {}
# Iterate over croncrete and many-to-many fields
for field in self._meta.concrete_fields + self._meta.many_to_many:
value = None
# If the value of the field is another model, fetch an instance of it
# Exception made of tags for which we just retrieve the list of them for later
# conversion to simple strings
if isinstance(field, ForeignKey):
value = self.__getattribute__(field.name)
elif isinstance(field, ManyToManyField):
value = list(self.__getattribute__(field.name).all())
elif isinstance(field, TaggableManager):
value = list(self.__getattribute__(field.name).all())
else:
value = self.__getattribute__(field.name)
# If the instance of a model as a to_dict() function, call it
if isinstance(value, TemplateModel):
data[field.name] = value.to_dict()
elif isinstance(value, list):
data[field.name] = []
for element in value:
if isinstance(element, TemplateModel):
data[field.name].append(element.to_dict())
else:
data[field.name].append(str(element))
else:
data[field.name] = value
return data
示例8: to_dict
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def to_dict(instance):
opts = instance._meta
data = {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if instance.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data
示例9: _model_to_dict
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def _model_to_dict(instance):
opts, data = getattr(instance, '_meta'), dict()
for f in opts.fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if instance.pk is None:
data[f.name] = []
else:
data[f.name] = [
item.pk for item in f.value_from_object(instance)]
elif isinstance(f, ForeignKey):
if getattr(instance, f.name):
data[f.name] = getattr(instance, f.name).__str__()
else:
data[f.name] = f.value_from_object(instance)
return data
示例10: reviewable_data_has_changed
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def reviewable_data_has_changed(obj, new_key_vals, exempt_fields=None):
"""
Check whether serialized data for the object has changed.
Args:
obj (Object): Object representing the persisted state
new_key_vals (dict_items): List of (key,value) tuples representing the new state
exempt_fields (list): List of field names where a change does not affect review status
Returns:
bool for whether data for any reviewable fields has changed
"""
changed = False
exempt_fields = exempt_fields or []
for key, new_value in [x for x in new_key_vals if x[0] not in exempt_fields]:
original_value = getattr(obj, key, None)
if isinstance(new_value, list):
field_class = obj.__class__._meta.get_field(key).__class__
original_value_elements = original_value.all()
if len(new_value) != original_value_elements.count():
changed = True
# Just use set compare since none of our fields require duplicates
elif field_class == ManyToManyField and set(new_value) != set(original_value_elements):
changed = True
elif field_class == SortedManyToManyField:
for new_value_element, original_value_element in zip(new_value, original_value_elements):
if new_value_element != original_value_element:
changed = True
elif new_value != original_value:
changed = True
return changed
示例11: post
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def post(self, request, *args, **kwargs):
try:
msg = _("%(model_name)s '%(instance)s' deleted.") % {
'model_name': self.verbose_name, 'instance': self.instance
}
self.delete_instance()
messages.success(request, msg)
return redirect(self.index_url)
except models.ProtectedError:
linked_objects = []
fields = self.model._meta.fields_map.values()
fields = (obj for obj in fields if not isinstance(
obj.field, ManyToManyField))
for rel in fields:
if rel.on_delete == models.PROTECT:
if isinstance(rel, OneToOneRel):
try:
obj = getattr(self.instance, rel.get_accessor_name())
except ObjectDoesNotExist:
pass
else:
linked_objects.append(obj)
else:
qs = getattr(self.instance, rel.get_accessor_name())
for obj in qs.all():
linked_objects.append(obj)
context = self.get_context_data(
protected_error=True,
linked_objects=linked_objects
)
return self.render_to_response(context)
示例12: model_to_dict
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def model_to_dict(instance, fields=None, exclude=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed in
the ``fields`` argument.
"""
# avoid a circular import
from django.db.models.fields.related import ManyToManyField
opts = instance._meta
data = {}
for f in opts.fields + opts.many_to_many:
if not f.editable:
continue
if fields and not f.name in fields:
continue
if exclude and f.name in exclude:
continue
if isinstance(f, ManyToManyField):
# If the object doesn't have a primary key yet, just use an empty
# list for its m2m fields. Calling f.value_from_object will raise
# an exception.
if instance.pk is None:
data[f.name] = []
else:
# MultipleChoiceWidget needs a list of pks, not object instances.
data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data
示例13: test_get_m2m_field
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def test_get_m2m_field(self):
field_info = self._details(Person, Person._meta.get_field('m2m_base'))
self.assertEqual(field_info[1:], (BasePerson, True, True))
self.assertIsInstance(field_info[0], related.ManyToManyField)
示例14: deserialize_field
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def deserialize_field(self, source, field_name):
method_name = 'deserialize_{0}'.format(field_name)
if hasattr(self, method_name):
return getattr(self, method_name)(source, field_name)
field = self.model._meta.get_field(field_name)
field_type_method_name = 'deserialize_type_{0}'.format(
field.__class__.__name__.lower())
if hasattr(self, field_type_method_name):
return getattr(self, field_type_method_name)(source, field_name)
val = source.get(field_name)
# datetime
typ = field.get_internal_type()
if val and typ in ('DateField', 'DateTimeField'):
return datetime.datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f')
if field.rel:
# M2M
if isinstance(field, ManyToManyField):
raise AttributeError
# FK, OtO
return self.nested_deserialize(field, source.get(field_name))
return source.get(field_name)
示例15: serialize_field
# 需要导入模块: from django.db.models.fields import related [as 别名]
# 或者: from django.db.models.fields.related import ManyToManyField [as 别名]
def serialize_field(self, instance, field_name):
method_name = 'serialize_{0}'.format(field_name)
if hasattr(self, method_name):
return getattr(self, method_name)(instance, field_name)
try:
field = self.model._meta.get_field(field_name)
except FieldDoesNotExist:
# Abstract field
pass
else:
field_type_method_name = 'serialize_type_{0}'.format(
field.__class__.__name__.lower())
if hasattr(self, field_type_method_name):
return getattr(self, field_type_method_name)(instance, field_name)
if field.rel:
# M2M
if isinstance(field, ManyToManyField):
return [self.nested_serialize(r)
for r in getattr(instance, field.name).all()]
rel = getattr(instance, field.name)
# FK, OtO
if rel: # should be a model instance
if self.cur_depth >= self.max_depth:
return
return self.nested_serialize(rel)
try:
return getattr(instance, field_name)
except AttributeError:
raise AttributeError("The serializer doesn't know how to serialize {0}, "
"please provide it a {1} method."
"".format(field_name, method_name))