For the given `many_to_many_relationships` dict mapping field names to
        a list of object instances, apply the instance listing to the `obj`s
        named many-to-many relationship field.
970344
def _write_related_m2m_relations(self, obj, many_to_many_relationships):
        
        for fieldname, related_objs in many_to_many_relationships.items():
            # TODO On PATCH avoid clearing existing relationships not provided?
            setattr(obj, fieldname, related_objs)
416952
def bind_fields_to_model_cls(cls, model_fields):
        """"""
        return dict(
            (field.name, field.bind_model_cls(cls)) for field in model_fields)
990703
def add_fields(self, field_dict):
    
    for key, field in field_dict.items():
      self.add_field(key, field)
799638
def contribute_to_class(self, cls, name):
        
        for field in cls._meta.many_to_many:
            if isinstance(field, self.__class__):
                e = "Multiple %s fields are not supported (%s.%s, %s.%s)" % (
                    self.__class__.__name__, cls.__name__, cls.__name__,
                    name, field.name)
                raise ImproperlyConfigured(e)
        self.related_field_name = name
        super(BaseGenericRelation, self).contribute_to_class(cls, name)
        # Not applicable to abstract classes, and in fact will break.
        if not cls._meta.abstract:
            for (name_string, field) in self.fields.items():
                if "%s" in name_string:
                    name_string = name_string % name
                extant_fields = cls._meta._forward_fields_map
                if name_string in extant_fields:
                    continue
                if field.verbose_name is None:
                    field.verbose_name = self.verbose_name
                cls.add_to_class(name_string, copy(field))
            # Add a getter function to the model we can use to retrieve
            # the field/manager by name.
            getter_name = "get_%s_name" % self.__class__.__name__.lower()
            cls.add_to_class(getter_name, lambda self: name)

            sender = self.rel.to
            post_save.connect(self._related_items_changed, sender=sender)
            post_delete.connect(self._related_items_changed, sender=sender)
547793
def insert_many(objects, using="default"):
    
    if not objects:
        return

    import django.db.models
    from django.db import connections
    from django.db import transaction
    con = connections[using]

    model = objects[0].__class__
    fields = [f for f in model._meta.fields
              if not isinstance(f, django.db.models.AutoField)]
    parameters = []
    for o in objects:
        params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
                       for f in fields)
        parameters.append(params)

    table = model._meta.db_table
    column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
    placeholders = ",".join(("%s",) * len(fields))
    con.cursor().executemany("insert into %s (%s) values (%s)"
                             % (table, column_names, placeholders), parameters)
    transaction.commit_unless_managed(using=using)
1374764
def get_related_fields(model_class, field_name, path=""):
    
    if field_name:
        field, model, direct, m2m = _get_field_by_name(model_class, field_name)
        if direct:
            # Direct field
            try:
                new_model = _get_remote_field(field).parent_model()
            except AttributeError:
                new_model = _get_remote_field(field).model
        else:
            # Indirect related field
            if hasattr(field, 'related_model'):  # Django>=1.8
                new_model = field.related_model
            else:
                new_model = field.model()

        path += field_name
        path += '__'
    else:
        new_model = model_class

    new_fields = get_relation_fields_from_model(new_model)
    model_ct = ContentType.objects.get_for_model(new_model)

    return (new_fields, model_ct, path)
343735
def get_relationships(schema, model_field=False):
    
    relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)]

    if model_field is True:
        relationships = [get_model_field(schema, key) for key in relationships]

    return relationships
209724
def handle_fk_field(self, obj, field):
        
        self._start_relational_field(field)
        related = getattr(obj, field.name)
        if related is not None:
            if self.use_natural_keys and hasattr(related, 'natural_key'):
                # If related object has a natural key, use it
                related = related.natural_key()
                # Iterable natural keys are rolled out as subelements
                for key_value in related:
                    self.xml.startElement("natural", {})
                    self.xml.characters(smart_unicode(key_value))
                    self.xml.endElement("natural")
            else:
                if field.rel.field_name == related._meta.pk.name:
                    # Related to remote object via primary key
                    related = related._get_pk_val()
                else:
                    # Related to remote object via other field
                    related = getattr(related, field.rel.field_name)
                self.xml.characters(smart_unicode(related))
        else:
            self.xml.addQuickElement("None")
        self.xml.endElement("field")
898302
def contribute_to_related_class(self, cls, related):
        
        # Internal FK's - i.e., those with a related name ending with '+' -
        # and swapped models don't get a related descriptor.
        super(VersionedForeignKey, self).contribute_to_related_class(cls,
                                                                     related)
        accessor_name = related.get_accessor_name()
        if hasattr(cls, accessor_name):
            setattr(cls, accessor_name,
                    VersionedReverseManyToOneDescriptor(related))
1356793
def expand_attribute_names_for_aggregates(attribute_names)
      attribute_names.map { |attribute_name|
        unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
          aggregate_mapping(aggregation).map do |field_attr, _|
            field_attr.to_sym
          end
        else
          attribute_name.to_sym
        end
      }.flatten
    end
702097
public function index()
    {
        $this->loadModel('Field.FieldInstances');
        $instances = $this->_getInstances();
        if (count($instances) == 0) {
            $this->Flash->warning(__d('field', 'There are no field attached yet.'));
        }

        $this->title(__d('field', 'Fields List'));
        $this->set('instances', $instances);
    }
857953
def formfield_for_manytomany(self, db_field, request, **kwargs):
        '''
        
        '''
        db = kwargs.get('using')
        kwargs['queryset'] = kwargs.get('queryset', self.get_field_queryset(db, db_field, request))
        return super(AccessControlMixin, self).formfield_for_manytomany(db_field, request, **kwargs)
1233994
def models_from_model(model, include_related=False, exclude=None):
    ''''''
    if exclude is None:
        exclude = set()
    if model and model not in exclude:
        exclude.add(model)
        if isinstance(model, ModelType) and not model._meta.abstract:
            yield model
            if include_related:
                exclude.add(model)
                for field in model._meta.fields:
                    if hasattr(field, 'relmodel'):
                        through = getattr(field, 'through', None)
                        for rmodel in (field.relmodel, field.model, through):
                            for m in models_from_model(
                                    rmodel, include_related=include_related,
                                    exclude=exclude):
                                yield m
                for manytomany in model._meta.manytomany:
                    related = getattr(model, manytomany)
                    for m in models_from_model(related.model,
                                               include_related=include_related,
                                               exclude=exclude):
                        yield m
        elif not isinstance(model, ModelType) and isclass(model):
            # This is a class which is not o ModelType
            yield model
111115
def _track_class_related_field(cls, field):
    
    # field = field on current model
    # related_field = field on related model
    (field, related_field) = field.split('__', 1)
    field_obj = cls._meta.get_field(field)
    related_cls = field_obj.remote_field.model
    related_name = field_obj.remote_field.get_accessor_name()

    if not hasattr(related_cls, '_tracked_related_fields'):
        setattr(related_cls, '_tracked_related_fields', {})
    if related_field not in related_cls._tracked_related_fields.keys():
        related_cls._tracked_related_fields[related_field] = []

    # There can be several field from different or same model
    # related to a single model.
    # Thus _tracked_related_fields will be of the form:
    # {
    #     'field name on related model': [
    #         ('field name on current model', 'field name to current model'),
    #         ('field name on another model', 'field name to another model'),
    #         ...
    #     ],
    #     ...
    # }

    related_cls._tracked_related_fields[related_field].append(
        (field, related_name)
    )
    _add_signals_to_cls(related_cls)
    # Detect m2m fields changes
    if isinstance(related_cls._meta.get_field(related_field), ManyToManyField):
        m2m_changed.connect(
            tracking_m2m,
            sender=getattr(related_cls, related_field).through,
            dispatch_uid=repr(related_cls),
        )
586814
def include(self, *fields, **kwargs):
        
        clone = self._clone()

        # Preserve the stickiness of related querysets
        # NOTE: by default _clone will clear this attribute
        # .include does not modify the actual query, so we
        # should not clear `filter_is_sticky`
        if self.query.filter_is_sticky:
            clone.query.filter_is_sticky = True

        clone._include_limit = kwargs.pop('limit_includes', None)
        assert not kwargs, '"limit_includes" is the only accepted kwargs. Eat your heart out 2.7'

        # Copy the behavior of .select_related(None)
        if fields == (None, ):
            for field in clone._includes.keys():
                clone.query._annotations.pop('__{}'.format(field.name), None)
            clone._includes.clear()
            return clone

        # Parse everything the way django handles joins/select related
        # Including multiple child fields ie .include(field1__field2, field1__field3)
        # turns into {field1: {field2: {}, field3: {}}
        for name in fields:
            ctx, model = clone._includes, clone.model
            for spl in name.split('__'):
                field = model._meta.get_field(spl)
                if isinstance(field, ForeignObjectRel) and field.is_hidden():
                    raise ValueError('Hidden field "{!r}" has no descriptor and therefore cannot be included'.format(field))
                model = field.related_model
                ctx = ctx.setdefault(field, OrderedDict())

        for field in clone._includes.keys():
            clone._include(field)

        return clone
811562
def related_items_changed(self, instance, related_manager):
        
        assigned = related_manager.select_related("keyword")
        keywords = " ".join([str(a.keyword) for a in assigned])
        string_field_name = list(self.fields.keys())[0] % \
                            self.related_field_name
        if getattr(instance, string_field_name) != keywords:
            setattr(instance, string_field_name, keywords)
            instance.save()
1104319
def apply(self, collection, ops, resource=None, **kwargs):
        """"""
        mfield = self.mfield or resource.meta.model._meta.fields.get(self.field.attribute)
        if mfield:
            collection = collection.where(*[op(mfield, val) for op, val in ops])
        return collection