Get foreign keys and models they refer to, so we can pre-process
        the data for load_bulk
979220
def get_foreign_keys(cls):
        
        foreign_keys = {}
        for field in cls._meta.fields:
            if (
                field.get_internal_type() == 'ForeignKey' and
                field.name != 'parent'
            ):
                if django.VERSION >= (1, 9):
                    foreign_keys[field.name] = field.remote_field.model
                else:
                    foreign_keys[field.name] = field.rel.to
        return foreign_keys
942311
def fetch_object(self, model_id):
        """"""
        pk_field_instance = getattr(self.object_class, self.pk_field)
        qs = self.object_class.query.filter(pk_field_instance == model_id)
        model = qs.one_or_none()
        if not model:
            raise ReferenceNotFoundError
        return model
656972
def bulk_get(cls, imports, api=None):
        
        api = api or cls._API
        import_ids = [Transform.to_import(import_) for import_ in imports]
        data = {'import_ids': import_ids}

        response = api.post(url=cls._URL['bulk_get'], data=data)
        return ImportBulkRecord.parse_records(response=response, api=api)
202742
public function loadHasRelations($name, $foreignKey, $callback = null, $storeKey = null)
    {
        $storeKey = $storeKey ? : $name;
        if (!isset($this->relations[$storeKey])) {
            $keys = array_unique($this->pluck($this->table->getPrimaryKey()));

            if (count($keys) > 0) {
                $relationRows = $this->table->similarTable($name);
                if (count($keys) === 1) {
                    $relationRows->where("`{$foreignKey}` = ?", $keys[0]);
                } else {
                    $relationRows->whereIn($foreignKey, $keys);
                }
                if ($callback) {
                    Coroutine::callUserFuncArray($callback, [$relationRows]);
                }
                $relationRows = $relationRows->rows();
            } else {
                $relationRows = new Rows([], $this->table->similarTable($name));
            }
            $this->relations[$storeKey] = $relationRows;
        }
        return $this->relations[$storeKey];
    }
1134548
def get_model_names(app_label, models):
    
    return dict(
        (model, get_model_name(app_label, model))
        for model in models
    )
924102
def read_data(self, **kwargs):
        
        model = get_model(kwargs['app_label'], kwargs['model_name'])

        return model.objects.get(trigger_id=kwargs['trigger_id'])
1188652
def _get_eager_model_keys(self, models):
        
        keys = []

        for model in models:
            value = getattr(model, self._foreign_key)

            if value is not None and value not in keys:
                keys.append(value)

        if not len(keys):
            return [0]

        return keys
854580
private function relationData()
    {
        $onData = collect($this->data)->reject(function ($value, $key) {
            return !str_contains($key, 'on');
        });

        $foreignKeys = collect($this->data)->reject(function ($value, $key) {
            return !str_contains($key, 'tbl');
        });

        $this->onData = array_values($onData->toArray());

        $this->foreignKeys = array_values($foreignKeys->toArray());
    }
1122742
def get_related_ids(self):
        
        related = self.get_related()

        full_key = related.get_qualified_key_name()

        return self.get_query().select(full_key).lists(related.get_key_name())
591746
def get_model_ids_to_fetch(events, context_hints_per_source):
    
    number_types = (complex, float) + six.integer_types
    model_ids_to_fetch = defaultdict(set)

    for event in events:
        context_hints = context_hints_per_source.get(event.source, {})
        for context_key, hints in context_hints.items():
            for d, value in dict_find(event.context, context_key):
                values = value if isinstance(value, list) else [value]
                model_ids_to_fetch[get_model(hints['app_name'], hints['model_name'])].update(
                    v for v in values if isinstance(v, number_types)
                )

    return model_ids_to_fetch
494422
def dump_foreign_key(foreign_key)
      parts = [
        "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}",
        remove_prefix_and_suffix(foreign_key.to_table).inspect,
      ]

      if foreign_key.column != foreign_key_column_for(foreign_key.to_table)
        parts << "column: #{foreign_key.column.inspect}"
      end

      if foreign_key.custom_primary_key?
        parts << "primary_key: #{foreign_key.primary_key.inspect}"
      end

      if foreign_key.name !~ /^fk_rails_[0-9a-f]{10}$/
        parts << "name: #{foreign_key.name.inspect}"
      end

      parts << "on_update: #{foreign_key.on_update.inspect}" if foreign_key.on_update
      parts << "on_delete: #{foreign_key.on_delete.inspect}" if foreign_key.on_delete

      parts.join(', ')
    end
591914
def get_query_parts(self):
        
        selects = []
        aliases = []
        froms = []
        wheres = []
        sorts = []
        groups_by = []
        params = []
        app_model_labels = None
        lookup_cast = self._db_operations.lookup_cast
        qn = self._db_operations.quote_name
        uqn = self._unquote_name
        for data in self.cleaned_data:
            if not ("model" in data and "field" in data):
                break
            model = data["model"]
            # HACK: Workaround to handle tables created
            #       by django for its own
            if not app_model_labels:
                app_models = get_models(include_auto_created=True,
                                        include_deferred=True)
                app_model_labels = [u"%s_%s" % (a._meta.app_label,
                                                a._meta.model_name)
                                    for a in app_models]
            if model in app_model_labels:
                position = app_model_labels.index(model)
                model = app_models[position]._meta.db_table
                self._models[model] = app_models[position]
            field = data["field"]
            show = data["show"]
            alias = data["alias"]
            criteria = data["criteria"]
            sort = data["sort"]
            group_by = data["group_by"]
            operator, over = criteria
            olower = operator.lower()
            if 'contains' in olower:
                over = '%' + over + '%'
            elif 'endswith' in olower:
                over = '%' + over
            elif 'startswith' in olower:
                over = over + '%'

            is_join = operator.lower() == 'join'
            db_field = self.get_db_field(model, field, qn, is_join=is_join)
            if show and not is_join:
                selects.append(db_field)
            if alias is not None and not is_join:
                aliases.append(alias)
            if sort:
                sorts.append(db_field + ('' if sort == 'asc' else ' DESC'))
            if group_by:
                groups_by.append(db_field)
            if all(criteria):
                if is_join:
                    over_split = over.lower().rsplit(".", 1)
                    join_model = qn(over_split[0].replace(".", "_"))
                    join_field = qn(over_split[1])
                    join = u"%s.%s = %s" % (join_model, join_field, db_field)
                    if (join not in wheres
                            and uqn(join_model) in self._db_table_names):
                        wheres.append(join)
                        if join_model not in froms:
                            froms.append(join_model)
                    # join_select = u"%s.%s" % (join_model, join_field)
                    # if join_select not in selects:
                    #     selects.append(join_select)
                elif operator in self._db_operators:
                    # db_operator = self._db_operators[operator] % over
                    db_operator = self._db_operators[operator]
                    lookup = self._get_lookup(operator, over)
                    params.append(lookup)
                    wheres.append(u"%s %s"
                                  % (lookup_cast(operator) % db_field,
                                     db_operator))
                elif operator in self._custom_operators:
                    CustOperator = self._custom_operators[operator]
                    custom_operator = CustOperator(db_field, operator, over)

                    # make sure the operators params are iterable:
                    custom_params = custom_operator.get_params()
                    if isinstance(custom_params, collections.Iterable):
                        params += custom_params
                    else:
                        params += [custom_params, ]

                    # make sure the operators wheres are iterable:
                    custom_wheres = custom_operator.get_wheres()
                    if isinstance(custom_wheres, collections.Iterable):
                        wheres += custom_wheres
                    else:
                        wheres += [custom_wheres, ]

            if qn(model) not in froms and model in self._db_table_names:
                froms.append(qn(model))
        return selects, aliases, froms, wheres, sorts, groups_by, params
227223
def _gather_keys_by_type(self, type):
        
        foreign = self._foreign_key

        keys = (
            BaseCollection.make(list(self._dictionary[type].values()))
            .map(lambda models: getattr(models[0], foreign))
            .unique()
        )

        return keys
179151
def _get_custom_models(models):
    """"""
    if models is None:
        models = Model.model_class_reverse_map.values()

    custom_models = OrderedDict()
    for cls in models:
        impl = getattr(cls, "__implementation__", None)

        if impl is not None:
            model = CustomModel(cls)
            custom_models[model.full_name] = model

    if not custom_models:
        return None
    return custom_models
328874
def get_fk_many_from_list(
            self, object_list, fkmany, fkmany_class, key_attr):
        """"""

        object_dict = {o.get(key_attr): o for o in object_list}
        object_keys = [o.get(key_attr) for o in object_list]

        # delete fks that have been removed
        fkmany = [o for o in fkmany if getattr(o, key_attr) in object_keys]

        # sync existing fks
        for fk in fkmany:
            obj = object_dict.get(getattr(fk, key_attr))
            for attr in fkmany_class.update_from_object_fields:
                setattr(fk, attr, obj.get(attr))

        # create new fks
        new_fks = []
        orm_keys = [getattr(o, key_attr) for o in fkmany]
        for obj in object_list:
            key = obj.get(key_attr)
            if key not in orm_keys:
                del obj['id']
                orm_kwargs = {}
                for k in obj:
                    if (
                        k in fkmany_class.update_from_object_fields and
                        k in obj
                    ):
                        orm_kwargs[k] = obj[k]
                new_obj = fkmany_class(**orm_kwargs)
                new_fks.append(new_obj)
        fkmany += new_fks
        return fkmany
318862
def _get_all(self):
        
        return [self._to_dict(row) for row in models.User.objects.all()]
259741
def get_db_references(cls, entry):
        
        db_refs = []

        for db_ref in entry.iterfind("./dbReference"):

            db_ref_dict = {'identifier': db_ref.attrib['id'], 'type_': db_ref.attrib['type']}
            db_refs.append(models.DbReference(**db_ref_dict))

        return db_refs