Loads related object in a dynamic attribute and returns it.
162038
def _load_source_object(self):
		
		if hasattr(self, "source_obj"):
			self.source_text = getattr(self.source_obj, self.field)
			return self.source_obj

		self._load_source_model()
		self.source_obj = self.source_model.objects.get(id=self.object_id)
		return self.source_obj
1178415
def get_attribute(self, code, default=None):
        """"""
        try:
            return self.get(code=code).value
        except models.ObjectDoesNotExist:
            return default
955854
def _get_relationship_data(self):
        """"""
        relationship_field = request.path.split('/')[-1].replace('-', '_')

        if relationship_field not in get_relationships(self.schema):
            raise RelationNotFound("{} has no attribute {}".format(self.schema.__name__, relationship_field))

        related_type_ = self.schema._declared_fields[relationship_field].type_
        related_id_field = self.schema._declared_fields[relationship_field].id_field
        model_relationship_field = get_model_field(self.schema, relationship_field)

        return relationship_field, model_relationship_field, related_type_, related_id_field
936896
def dynamic_load(name):
    
    pieces = name.split('.')
    item = pieces[-1]
    mod_name = '.'.join(pieces[:-1])

    mod = __import__(mod_name, globals(), locals(), [item])
    return getattr(mod, item)
379693
def get_model_at_related_field(model, attr):
    

    field = model._meta.get_field(attr)

    if hasattr(field, 'related_model'):
        return field.related_model

    raise ValueError("{model}.{attr} ({klass}) is not a relationship field.".format(**{
        'model': model.__name__,
        'attr': attr,
        'klass': field.__class__.__name__,
    }))
163412
def _get_dynamic_attr(self, attname, obj, default=None):
        
        try:
            attr = getattr(self, attname)
        except AttributeError:
            return default
        if callable(attr):
            # Check co_argcount rather than try/excepting the function and
            # catching the TypeError, because something inside the function
            # may raise the TypeError. This technique is more accurate.
            try:
                code = six.get_function_code(attr)
            except AttributeError:
                code = six.get_function_code(attr.__call__)
            if code.co_argcount == 2:       # one argument is 'self'
                return attr(obj)
            else:
                return attr()
        return attr
549007
def load(cls, cache_key, deserializer, key_attr):
        
        items = unitdata.kv().get(cache_key) or []
        return cls(cache_key,
                   [deserializer(item) for item in items],
                   key_attr)
1185473
def get_relationship(self, attribute):
        
        rel = self.__relationships.get(attribute.entity_attr)
        if rel is None:
            rel = LazyDomainRelationship(self, attribute,
                                         direction=
                                            self.relationship_direction)
            self.__relationships[attribute.entity_attr] = rel
        return rel
891028
protected function loadRelatedData()
    {
        $settings = [];
        $contextSettings = [];
        if (is_object($this->xPDOSimpleObject)) {
            /** @var array of \modContextSetting $contextSettings */
            $contextSettings = $this->xPDOSimpleObject->getMany('ContextSettings');
        }
        /** @var \modContextSetting $setting */
        foreach ($contextSettings as $setting) {
            $settings[] = $this->makePortableData($setting->toArray());
        }

        $this->related_data = [
            'settings' => $settings
        ];

        // Calls on the event: OnBlendLoadRelatedData
        parent::loadRelatedData();
    }
692625
def get_context(self, name, value, attrs):
        
        context = super(DynamicRawIDWidget, self).get_context(
            name, value, attrs
        )
        model = self.rel.model if VERSION[0] == 2 else self.rel.to
        related_url = reverse(
            'admin:{0}_{1}_changelist'.format(
                model._meta.app_label, model._meta.object_name.lower()
            ),
            current_app=self.admin_site.name,
        )

        params = self.url_parameters()
        if params:
            url = u'?' + u'&'.join(
                [u'{0}={1}'.format(k, v) for k, v in params.items()]
            )
        else:
            url = u''
        if "class" not in attrs:
            attrs[
                'class'
            ] = (
                'vForeignKeyRawIdAdminField'
            )  # The JavaScript looks for this hook.
        app_name = model._meta.app_label.strip()
        model_name = model._meta.object_name.lower().strip()

        context.update(
            {
                'name': name,
                'app_name': app_name,
                'model_name': model_name,
                'related_url': related_url,
                'url': url,
            }
        )
        return context
68931
def lookup(self, name):
        

        if name in self.attributes():
            return getattr(self, IMPL_PREFIX + name)
        raise exceptions.AttributeInferenceError(target=self._instance, attribute=name)
571
def load(attributes, remove_root=false)
      attributes = attributes ? attributes.stringify_keys : {}
      self.class.belongs_to_with_parents.each do |belongs_to_param|
        attributes["#{belongs_to_param}_id"] ||= prefix_options["#{belongs_to_param}_id".intern]

        # also set prefix attributes as real attributes. Otherwise,
        # belongs_to attributes will be stripped out of the response
        # even if we aren't actually using the association.
        @attributes["#{belongs_to_param}_id"] = attributes["#{belongs_to_param}_id"]
      end
      super(attributes, remove_root)
    end
236044
def igetattr(self, name, context=None, class_context=True):
        
        # set lookup name since this is necessary to infer on import nodes for
        # instance
        context = contextmod.copy_context(context)
        context.lookupname = name
        try:
            attr = self.getattr(name, context, class_context=class_context)[0]
            for inferred in bases._infer_stmts([attr], context, frame=self):
                # yield Uninferable object instead of descriptors when necessary
                if not isinstance(inferred, node_classes.Const) and isinstance(
                    inferred, bases.Instance
                ):
                    try:
                        inferred._proxied.getattr("__get__", context)
                    except exceptions.AttributeInferenceError:
                        yield inferred
                    else:
                        yield util.Uninferable
                else:
                    yield function_to_method(inferred, self)
        except exceptions.AttributeInferenceError as error:
            if not name.startswith("__") and self.has_dynamic_getattr(context):
                # class handle some dynamic attributes, return a Uninferable object
                yield util.Uninferable
            else:
                raise exceptions.InferenceError(
                    error.message, target=self, attribute=name, context=context
                )
239321
def get_for(self, dynamic_part):
        
        if not hasattr(self, '_instance'):
            raise ImplementationError('"get_for" can be used only on a bound field')
        name = self.get_name_for(dynamic_part)
        return self._instance.get_field(name)
1071638
def load_object_by_name(obj_name):
    
    parts = obj_name.split('.')
    t = __import__('.'.join(parts[:-1]), fromlist=(parts[-1],))
    return getattr(t, parts[-1])
824229
protected function loadModelsManyToManyVia($attribute)
    {
        $data = $this->relationalData[$attribute];

        $activeQuery = $data['activeQuery'];
        /** @var ActiveRecord $class */
        $class = $activeQuery->modelClass;

        if (!is_object($activeQuery->via[1])) {
            throw new RelationException('via condition for attribute ' . $attribute . ' cannot must be object');
        }

        $via = $activeQuery->via[1];
        $junctionGetter = 'get' . ucfirst($activeQuery->via[0]);
        /** @var ActiveRecord $junctionModelClass */
        $data['junctionModelClass'] = $junctionModelClass = $via->modelClass;
        $data['junctionTable'] = $junctionModelClass::tableName();

        list($data['junctionColumn']) = array_keys($via->link);
        list($data['relatedColumn']) = array_values($activeQuery->link);
        $junctionColumn = $data['junctionColumn'];
        $relatedColumn = $data['relatedColumn'];

        if (!empty($data['data'])) {
            // make sure what all model's ids from POST exists in database
            $countManyToManyModels = $class::find()->where([$class::primaryKey()[0] => $data['data']])->count();
            if ($countManyToManyModels != count($data['data'])) {
                throw new RelationException('Related records for attribute ' . $attribute . ' not found');
            }
            // create new junction models
            foreach ($data['data'] as $relatedModelId) {
                $junctionModel = new $junctionModelClass(
                    array_merge(
                        !ArrayHelper::isAssociative($via->on) ? [] : $via->on,
                        [$junctionColumn => $this->owner->getPrimaryKey()]
                    )
                );
                $junctionModel->$relatedColumn = $relatedModelId;
                if (isset($this->relations[$attribute]) && is_callable($this->relations[$attribute])) {
                    $junctionModel = call_user_func($this->relations[$attribute], $junctionModel, $relatedModelId);
                }
                $data['newModels'][] = $junctionModel;
            }
        }

        $data['oldModels'] = $this->owner->$junctionGetter()->all();

        $this->relationalData[$attribute] = $data;
    }
642960
protected function loadModelsOneToMany($attribute)
    {
        $data = $this->relationalData[$attribute];
        
        $activeQuery = $data['activeQuery'];
        $class = $activeQuery->modelClass;

        // default query conditions
        $params = !ArrayHelper::isAssociative($activeQuery->on) ? [] : $activeQuery->on;
        // one-to-many
        foreach ($activeQuery->link as $childAttribute => $parentAttribute) {
            $params[$childAttribute] = $this->owner->$parentAttribute;
        }

        if (!empty($data['data'])) {
            foreach ($data['data'] as $attributes) {
                $model = new $class(
                    array_merge(
                        $params,
                        ArrayHelper::isAssociative($attributes) ? $attributes : []
                    )
                );
                if (isset($this->relations[$attribute]) && is_callable($this->relations[$attribute])) {
                    $model = call_user_func($this->relations[$attribute], $model, $attributes);
                }
                $data['newModels'][] = $model;
            }
        }

        $this->relationalData[$attribute] = $data;
    }