create DB objects related to a base object
            obj:            a base object to create related
            related:        dict mapping field names to lists of related objects
            subfield_list:  where to get the next layer of subfields
195637
def _create_related(self, obj, related, subfield_dict):
        
        for field, items in related.items():
            subobjects = []
            all_subrelated = []
            Subtype, reverse_id_field, subsubdict = subfield_dict[field]
            for order, item in enumerate(items):
                # pull off 'subrelated' (things that are related to this obj)
                subrelated = {}
                for subfield in subsubdict:
                    subrelated[subfield] = item.pop(subfield)

                if field in self.preserve_order:
                    item['order'] = order

                item[reverse_id_field] = obj.id

                try:
                    subobjects.append(Subtype(**item))
                    all_subrelated.append(subrelated)
                except Exception as e:
                    raise DataImportError('{} while importing {} as {}'.format(e, item, Subtype))

            # add all subobjects at once (really great for actions & votes)
            try:
                Subtype.objects.bulk_create(subobjects)
            except Exception as e:
                raise DataImportError('{} while importing {} as {}'.format(e, subobjects, Subtype))

            # after import the subobjects, import their subsubobjects
            for subobj, subrel in zip(subobjects, all_subrelated):
                self._create_related(subobj, subrel, subsubdict)
139897
def create_from_assocs(self, assocs, **args):
        
        amap = defaultdict(list)
        subject_label_map = {}
        for a in assocs:
            subj = a['subject']
            subj_id = subj['id']
            subj_label = subj['label']
            subject_label_map[subj_id] = subj_label
            if not a['negated']:
                amap[subj_id].append(a['object']['id'])

        aset = AssociationSet(subject_label_map=subject_label_map, association_map=amap, **args)
        aset.associations_by_subj = defaultdict(list)
        aset.associations_by_subj_obj = defaultdict(list)
        for a in assocs:
            sub_id = a['subject']['id']
            obj_id = a['object']['id']
            aset.associations_by_subj[sub_id].append(a)
            aset.associations_by_subj_obj[(sub_id,obj_id)].append(a)

        return aset
410513
def _attach_to_model(self, model):
        
        super(RelatedFieldMixin, self)._attach_to_model(model)

        if model.abstract:
            # do not manage the relation if it's an abstract model
            return

        # now, check related_name and save the relation in the database

        # get related parameters to identify the relation
        self.related_name = self._get_related_name()
        self.related_to = self._get_related_model_name()

        # create entry for the model in the _relations list of the database
        if not hasattr(self.database, '_relations'):
            self.database._relations = {}
        self.database._relations.setdefault(self.related_to, [])

        # check unicity of related name for related model
        self._assert_relation_does_not_exists()

        # the relation didn't exists, we can save it
        relation = (self._model._name, self.name, self.related_name)
        self.database._relations[self.related_to].append(relation)
869769
def _create_update_tracking_related_event(instance):
    
    events = {}
    # Create a dict mapping related model field to modified fields
    for field, related_fields in instance._tracked_related_fields.items():
        if not isinstance(instance._meta.get_field(field), ManyToManyField):
            if isinstance(instance._meta.get_field(field), ForeignKey):
                # Compare pk
                value = getattr(instance, '{0}_id'.format(field))
            else:
                value = getattr(instance, field)
            if instance._original_fields[field] != value:
                for related_field in related_fields:
                    events.setdefault(related_field, []).append(field)

    # Create the events from the events dict
    for related_field, fields in events.items():
        try:
            related_instances = getattr(instance, related_field[1])
        except ObjectDoesNotExist:
            continue

        # FIXME: isinstance(related_instances, RelatedManager ?)
        if hasattr(related_instances, 'all'):
            related_instances = related_instances.all()
        else:
            related_instances = [related_instances]
        for related_instance in related_instances:
            event = _create_event(related_instance, UPDATE)
            for field in fields:
                fieldname = '{0}__{1}'.format(related_field[0], field)
                _create_tracked_field(
                    event, instance, field, fieldname=fieldname
                )
1130276
def to_representation(self, obj):
        
        kwargs = None
        for field in self.lookup_fields:
            if hasattr(obj, field):
                kwargs = {field: getattr(obj, field)}
                break
        if kwargs is None:
            raise AttributeError('Related object does not have any of lookup_fields')
        request = self._get_request()
        return request.build_absolute_uri(reverse(self._get_url(obj), kwargs=kwargs))
208799
def build_relational_field(self, field_name, relation_info):
        
        field_class = self.serializer_related_field
        field_kwargs = get_relation_kwargs(field_name, relation_info)

        to_field = field_kwargs.pop('to_field', None)
        if to_field and not relation_info.related_model._meta.get_field(to_field).primary_key:
            field_kwargs['slug_field'] = to_field
            field_class = self.serializer_related_to_field

        # `view_name` is only valid for hyperlinked relationships.
        if not issubclass(field_class, HyperlinkedRelatedField):
            field_kwargs.pop('view_name', None)

        return field_class, field_kwargs
901952
def connected_objects(self, from_obj):
        
        return self.to_content_type.get_all_objects_for_this_type(pk__in=self.connected_object_ids(from_obj))
1025154
def connected_to_objects(self, to_obj):
        
        return self.from_content_type.get_all_objects_for_this_type(pk__in=self.connected_to_object_ids(to_obj))
278176
def bulk_related_objects(self, objs, using=DEFAULT_DB_ALIAS):
        
        if self.delete_related:
            return super(AuditlogHistoryField, self).bulk_related_objects(objs, using)

        # When deleting, Collector.collect() finds related objects using this
        # method.  However, because we don't want to delete these related
        # objects, we simply return an empty list.
        return []
251812
def configure_field(self, field):
        """"""
        from .models import Indexable

        # This is for reverse relations, which do not have a db column
        if field.auto_created and field.is_relation:
            if isinstance(field, (ForeignObjectRel, ManyToOneRel)) and issubclass(field.related_model, Indexable):
                related_properties = field.related_model.search_objects.mapping.properties.properties.to_dict()
                self.field(field.name, {"type": "nested", "properties": related_properties})
                return

        if field.get_internal_type() == "ManyToManyField" and issubclass(field.rel.to, Indexable):

            related_properties = field.rel.to.search_objects.mapping.properties.properties.to_dict()
            self.field(field.name, {"type": "nested", "properties": related_properties})
            return

        if isinstance(field, models.ForeignKey):
            # This is a related field, so it should maybe be nested?

            # We only want to nest fields when they are indexable, and not parent pointers.
            if issubclass(field.rel.to, Indexable) and not field.rel.parent_link:

                related_properties = field.rel.to.search_objects.mapping.properties.properties.to_dict()
                self.field(field.name, {"type": "nested", "properties": related_properties})
                return

        db_column, attname = field.db_column, field.attname

        field_args = FIELD_MAPPINGS.get(field.get_internal_type())
        if field_args:
            self.field(db_column or attname, field_args)
        else:
            raise Warning("Can't find {}".format(field.get_internal_type()))
900353
def save_object_to_db(self,
                          obj: Any,
                          table: str,
                          fieldlist: Sequence[str],
                          is_new_record: bool) -> None:
        """"""
        if is_new_record:
            pkvalue = getattr(obj, fieldlist[0])
            if pkvalue is None:
                self.insert_object_into_db_pk_unknown(obj, table, fieldlist)
            else:
                self.insert_object_into_db_pk_known(obj, table, fieldlist)
        else:
            self.update_object_in_db(obj, table, fieldlist)
969680
def p_const_object_field_list(self, p):
        
        obj = p[1].copy()
        obj.update(p[2])
        p[0] = obj
1226311
def subfield_get(self, obj, type=None):
    
    if obj is None:
        return self
    return obj.__dict__[self.field.name]
387106
def _to_fields(self, *values):
        
        result = []
        for related_instance in values:
            if not isinstance(related_instance, model.RedisModel):
                related_instance = self.related_field._model(related_instance)
            result.append(getattr(related_instance, self.related_field.name))
        return result
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)
172062
def set_relation_many_to_many(self, obj, field_name, objs):
        ""
        relation = getattr(obj, field_name)
        if hasattr(relation, 'set'):
            relation.set(objs) # Django 2.x
        else:
            setattr(obj, field_name, objs)
785017
def instantiate_object_id_field(object_id_class_or_tuple=models.TextField):
    
    if isinstance(object_id_class_or_tuple, (list, tuple)):
        object_id_class, object_id_kwargs = object_id_class_or_tuple
    else:
        object_id_class = object_id_class_or_tuple
        object_id_kwargs = {}

    if not issubclass(object_id_class, models.fields.Field):
        raise TypeError('settings.%s must be a Django model field or (field, kwargs) tuple' % OBJECT_ID_TYPE_SETTING)
    if not isinstance(object_id_kwargs, dict):
        raise TypeError('settings.%s kwargs must be a dict' % OBJECT_ID_TYPE_SETTING)

    return object_id_class(db_index=True, **object_id_kwargs)