我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.ManyToManyRel()。
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_text(obj) for obj in value.all()]) else: return smart_text(value)
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_unicode(obj) for obj in value.all()]) else: return smart_unicode(value)
def lookup_needs_distinct(opts, lookup_path): """ Returns True if 'distinct()' should be used to query the given lookup path. """ field_name = lookup_path.split('__', 1)[0] field = opts.get_field_by_name(field_name)[0] if hasattr(field,'field'): _field = field.field else: _field = field if ((hasattr(field, 'rel') and isinstance(field.rel, models.ManyToManyRel)) or (isinstance(field, RelatedObject) and not _field.unique)): return True return False
def display_for_field(value, field): from xadmin.views.list import EMPTY_CHANGELIST_VALUE if field.flatchoices: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_unicode(obj) for obj in value.all()]) else: return value#smart_unicode(value)
def validate_local_fields(e, opts, field_name, fields): from django.db import models if not isinstance(fields, collections.Sequence): e.add(opts, 'all %s elements must be sequences' % field_name) else: for field in fields: try: f = opts.get_field(field, many_to_many=True) except models.FieldDoesNotExist: e.add(opts, '"%s" refers to %s, a field that doesn\'t exist.' % (field_name, field)) else: if isinstance(f.rel, models.ManyToManyRel): e.add(opts, '"%s" refers to %s. ManyToManyFields are not supported in %s.' % (field_name, f.name, field_name)) if f not in opts.local_fields: e.add(opts, '"%s" refers to %s. This is not in the same model as the %s statement.' % (field_name, f.name, field_name))
def lookup_needs_distinct(opts, lookup_path): """ Returns True if 'distinct()' should be used to query the given lookup path. """ field_name = lookup_path.split('__', 1)[0] field = opts.get_field(field_name) if ((hasattr(field, 'rel') and isinstance(field.rel, models.ManyToManyRel)) or (is_related_field(field) and not field.field.unique)): return True return False
def get_version_object(self, version): obj_version = version._object_version obj = obj_version.object obj._state.db = self.obj._state.db for field_name, pks in obj_version.m2m_data.items(): f = self.opts.get_field(field_name) if f.rel and isinstance(f.rel, models.ManyToManyRel): setattr(obj, f.name, f.rel.to._default_manager.get_query_set( ).filter(pk__in=pks).all()) detail = self.get_model_view(DetailAdminUtil, self.model, obj) return obj, detail
def get_field_instance(self, model, field_name): field = model._meta.get_field(field_name) field_kwargs = {'model': model, 'name': field.name} if field.is_relation: if not field.related_model: # GenericForeignKey return if self.excluded(field.related_model): return field_cls = RelationField field_kwargs['related_model'] = field.related_model else: field_cls = self.get_field_cls(field) if isinstance(field, (ManyToOneRel, ManyToManyRel, GenericRel)): # Django 1.8 doesn't have .null attribute for these fields field_kwargs['nullable'] = True else: field_kwargs['nullable'] = field.null field_kwargs['suggest_options'] = ( field.name in self.suggest_options.get(model, []) ) field_instance = field_cls(**field_kwargs) # Check if suggested options conflict with field type if field_cls != StrField and field_instance.suggest_options: for option in field_instance.get_options(): if isinstance(option, text_type): # Convert to StrField field_instance = StrField(**field_kwargs) return field_instance
def get_reverse_fields(model, local_field_names): for name, attr in model.__dict__.items(): # Don't duplicate any local fields if name in local_field_names: continue # Django =>1.9 uses 'rel', django <1.9 uses 'related' related = getattr(attr, 'rel', None) or \ getattr(attr, 'related', None) if isinstance(related, models.ManyToOneRel): yield (name, related) elif isinstance(related, models.ManyToManyRel) and not related.symmetrical: yield (name, related)
def display_for_field(value, field): from xadmin.defs import EMPTY_CHANGELIST_VALUE if field.flatchoices: if hasattr(value,'__iter__'): rets = [ dict(field.flatchoices).get(e, EMPTY_CHANGELIST_VALUE) for e in value] return ','.join(rets) else: return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField): return boolean_icon(value) elif value is None: return EMPTY_CHANGELIST_VALUE elif isinstance(field, models.DateTimeField): return formats.localize(tz_localtime(value)) elif isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) elif isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) elif isinstance(field, models.FloatField): return formats.number_format(value) elif isinstance(field.rel, models.ManyToManyRel): return ', '.join([smart_unicode(obj) for obj in value.all()]) else: return smart_unicode(value)
def get_version_object(self, version): obj_version = version.object_version obj = obj_version.object obj._state.db = self.obj._state.db for field_name, pks in obj_version.m2m_data.items(): f = self.opts.get_field(field_name) if f.rel and isinstance(f.rel, models.ManyToManyRel): setattr(obj, f.name, f.rel.to._default_manager.get_query_set( ).filter(pk__in=pks).all()) detail = self.get_model_view(DetailAdminUtil, self.model, obj) return obj, detail
def __init__(self, admin_view, lookup, value): self.admin_view = admin_view self.org_model = admin_view.model self.opts = admin_view.opts self.lookup = lookup self.value = value parts = lookup.split(LOOKUP_SEP) field = self.opts.get_field_by_name(parts[0])[0] if not hasattr(field, 'rel') and not isinstance(field, RelatedObject): raise Exception(u'Relate Lookup field must a related field') if hasattr(field, 'rel'): self.to_model = field.rel.to self.rel_name = field.rel.get_related_field().name self.is_m2m = isinstance(field.rel, models.ManyToManyRel) else: self.to_model = field.model self.rel_name = self.to_model._meta.pk.name self.is_m2m = False _manager = self.to_model._default_manager if hasattr(_manager, 'get_query_set'): to_qs = _manager.get_query_set() else: to_qs = _manager.get_queryset() self.to_objs = to_qs.filter(**{self.rel_name: value}).all() self.field = field
def _get_remote_field_name(field): reverse_field = True if isinstance(field, ( models.ManyToManyRel, models.ManyToOneRel, models.OneToOneRel, GenericRelation)) else False return str('{model}.{field}'.format( model=get_model_string(field.model), field=(field.related_name or '%s_set' % field.name if not isinstance(field, (models.OneToOneRel, GenericRelation)) else field.name)) if reverse_field else field.remote_field.field if not isinstance(field, GenericForeignKey) else str(field)).lower()
def get_cardinality_for_field(field): """ Returns the cardinality for ``field``. """ cardinalities = { models.ForeignKey: ZeroOrOne, models.ManyToOneRel: ZeroOrMore, models.OneToOneField: ZeroOrOne, models.OneToOneRel: ZeroOrOne, models.ManyToManyField: ZeroOrMore, models.ManyToManyRel: ZeroOrMore, GenericForeignKey: ZeroOrOne, GenericRelation: ZeroOrMore } return cardinalities[field.__class__]
def get_related_node_property_for_field(cls, field, meta_node=False): """ Get the relationship definition for the related node based on field. :param field: Field to inspect :param meta_node: If True, return the meta node for the related model, else return the model node. :returns: A ``RelationshipDefinition`` instance. """ from chemtrails.neoutils import ( __meta_cache__, __node_cache__, get_node_class_for_model, get_meta_node_class_for_model ) reverse_field = True if isinstance(field, ( models.ManyToManyRel, models.ManyToOneRel, models.OneToOneRel, GenericRelation)) else False class DynamicRelation(StructuredRel): type = StringProperty(default=field.__class__.__name__) is_meta = BooleanProperty(default=meta_node) remote_field = StringProperty(default=cls._get_remote_field_name(field)) target_field = StringProperty(default=str(getattr(field, 'target_field', '')).lower()) # NOTE: Workaround for #27 prop = cls.get_property_class_for_field(field.__class__) relationship_type = cls.get_relationship_type(field) related_model = field.model if isinstance(field, GenericForeignKey) else field.related_model if meta_node: klass = (__meta_cache__[related_model] if related_model in __meta_cache__ else get_meta_node_class_for_model(related_model)) return (prop(cls_name=klass, rel_type=relationship_type, model=DynamicRelation) # FIXME: Support cardinality for MetaNodes if not klass._is_ignored else None) else: klass = (__node_cache__[related_model] if reverse_field and related_model in __node_cache__ else get_node_class_for_model(related_model)) return (prop(cls_name=klass, rel_type=relationship_type, model=DynamicRelation, cardinality=cls.get_cardinality_for_field(field)) if not klass._is_ignored else None)
def get_version_object(self, version): obj_version = version.object_version obj = obj_version.object obj._state.db = self.obj._state.db for field_name, pks in list(obj_version.m2m_data.items()): f = self.opts.get_field(field_name) if f.rel and isinstance(f.rel, models.ManyToManyRel): setattr(obj, f.name, f.rel.to._default_manager.get_query_set( ).filter(pk__in=pks).all()) detail = self.get_model_view(DetailAdminUtil, self.model, obj) return obj, detail
def __init__(self, admin_view, lookup, value): self.admin_view = admin_view self.org_model = admin_view.model self.opts = admin_view.opts self.lookup = lookup self.value = value parts = lookup.split(LOOKUP_SEP) field = self.opts.get_field(parts[0]) if not is_related_field2(field): raise Exception('Relate Lookup field must a related field') if hasattr(field, 'rel'): self.to_model = field.rel.to self.rel_name = field.rel.get_related_field().name self.is_m2m = isinstance(field.rel, models.ManyToManyRel) else: self.to_model = field.model self.rel_name = self.to_model._meta.pk.name self.is_m2m = False to_qs = self.to_model._default_manager.get_queryset() self.to_objs = to_qs.filter(**{self.rel_name: value}).all() self.field = field