Find the related model & serialize it back

        If the parent resource of the related model doesn't
        exist then abort on a 404.
779419
def on_get(self, req, resp, rid, related):
        

        signals.pre_req.send(self.model)
        signals.pre_req_find.send(self.model)

        if not hasattr(self.model, related):
            abort(InvalidURL(**{
                'detail': 'The "%s" resource does not have a related '
                          'resource named "%s". This is an error, check '
                          'your spelling & retry.' % (self.rtype, related)
            }))

        model = find(self.model, rid)
        try:
            model_related = getattr(model, related).load()
        except AttributeError:
            model_related = None

        if isinstance(model_related, list):
            props = to_rest_models(model_related, includes=req.includes)
        elif model:
            props = to_rest_model(model_related, includes=req.includes)
        else:
            props = model_related

        resp.serialize(props)

        signals.post_req.send(self.model)
        signals.post_req_find.send(self.model)
1034816
def find_parent_id_for_component(self, slug):
        
        response = self.get_record(slug)

        if "parent" in response:
            return response["parent"]
        # resource was passed in, which has no higher-up record;
        # return the same ID
        else:
            return slug
1244107
def get(self, *args, **kwargs):
        """"""
        self.before_get(args, kwargs)

        relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()

        obj, data = self._data_layer.get_relationship(model_relationship_field,
                                                      related_type_,
                                                      related_id_field,
                                                      kwargs)

        result = {'links': {'self': request.path,
                            'related': self.schema._declared_fields[relationship_field].get_related_url(obj)},
                  'data': data}

        qs = QSManager(request.args, self.schema)
        if qs.include:
            schema = compute_schema(self.schema, dict(), qs, qs.include)

            serialized_obj = schema.dump(obj)
            result['included'] = serialized_obj.data.get('included', dict())

        final_result = self.after_get(result)

        return final_result
874711
def detect_missing_relations(self, obj, exc):
        
        missing = defaultdict(set)
        for name, err in exc.error_dict.items():
            # check if it was a relationship that doesnt exist locally
            pattern = r".+ with id (\d+) does not exist.+"
            m = re.match(pattern, str(err))
            if m:
                field = obj._meta.get_field(name)
                res = self.get_resource(field.related_model)
                missing[res].add(int(m.group(1)))
        return missing
932409
function relation (relatedModelName) {
    // if related model is not linked then lookup through immutable module
    if (!this.relations[relatedModelName] || !this.relations[relatedModelName].model) {
        // module name has Model appended
        var relatedModuleName = relatedModelName + 'Model'
        // check that module exists
        assert.ok(immutable.hasModule(relatedModuleName), 'module not found for relation '+relatedModelName)
        // get module
        var module = immutable.module(relatedModuleName)
        // get module meta data to get model
        var meta = module.meta
        // module must be ImmutableCoreModel
        assert.ok(meta.class === 'ImmutableCoreModel', 'invalid model for relation '+relatedModelName)
        // get model
        var relatedModel = meta.instance
        // if entry does not exist in relations create one
        if (!this.relations[relatedModelName]) {
            // require related model to have a relation to this model
            assert.ok(relatedModel.relations[this.name], 'no relation for '+relatedModelName)
            // build local relation from other model
            var relation = this.relations[relatedModelName] = _.cloneDeep(relatedModel.relations[this.name])
        }
        else {
            var relation = this.relations[relatedModelName]
        }
        // set model for relation
        relation.model = relatedModel
        // if relation has via and via model is not loaded then load it
        if (relation.via && !relation.viaModel) {
            // get via model module name
            var viaModuleName = relation.via+'Model'
            // check that module exists
            assert.ok(immutable.hasModule(viaModuleName), 'module not found for relation via '+relation.via)
            // get module
            var module = immutable.module(viaModuleName)
            // get module meta data to get model
            var meta = module.meta
            // module must be ImmutableCoreModel
            assert.ok(meta.class === 'ImmutableCoreModel', 'invalid model for relation via '+relation.via)
            // store model for relation via
            relation.viaModel = meta.instance
        }
        // set column names for via relation
        if (relation.via) {
            // get id column for model
            var idColumn = this.columnName('id')
            var originalIdColumn = this.columnName('originalId')
            // original id is on via table directly
            if (relation.viaModel.columns[originalIdColumn]) {
                relation.modelIdColumn = originalIdColumn
                relation.viaModelIdColumn = originalIdColumn
            }
            // original id is linked to via table on default column
            else if (relation.viaModel.columnName(originalIdColumn)) {
                relation.modelIdColumn = originalIdColumn
                relation.viaModelIdColumn = relation.viaModel.columnName(originalIdColumn)
            }
            // id column is on via table directly
            else if (relation.viaModel.columns[idColumn]) {
                relation.modelIdColumn = idColumn
                relation.viaModelIdColumn = idColumn
            }
            // id column is linked to via table on default column
            else if (relation.viaModel.columnName(idColumn)) {
                relation.modelIdColumn = idColumn
                relation.viaModelIdColumn = relation.viaModel.columnName(idColumn)
            }
            // error
            else {
                throw new Error('invalid id column for model '+this.name+' relation '+relatedModelName)
            }
            // get id column for relation model that links it to via model
            var relationIdColumn = relation.model.columnName('id')
            var relationOriginalIdColumn = relation.model.columnName('originalId')
            // relation original id is on via table directly
            if (relation.viaModel.columns[relationOriginalIdColumn]) {
                relation.relationIdColumn = relationOriginalIdColumn
                relation.viaRelationIdColumn = relationOriginalIdColumn
            }
            // relation original id is linked to via table on default column
            else if (relation.viaModel.columnName(relationOriginalIdColumn)) {
                relation.relationIdColumn = relationOriginalIdColumn
                relation.viaRelationIdColumn = relation.viaModel.columnName(relationOriginalIdColumn)
            }
            // relation id is on via table directly
            else if (relation.viaModel.columns[relationIdColumn]) {
                relation.relationIdColumn = relationIdColumn
                relation.viaRelationIdColumn = relationIdColumn
            }
            // relation id is linked to via table on default column
            else if (relation.viaModel.columnName(relationIdColumn)) {
                relation.relationIdColumn = relationIdColumn
                relation.viaRelationIdColumn = relation.viaModel.columnName(relationIdColumn)
            }
            // error
            else {
                throw new Error('invalid id column for model '+this.name+' relation '+relatedModelName)
            }
        }
        // set column names for direct relation
        else {
            // get id column for related model - direct relation can go either
            // way so need to test all possibilities
            var modelIdColumn = this.columnName('id')
            var modelOriginalIdColumn = this.columnName('originalId')
            var relationIdColumn = relation.model.columnName('id')
            var relationOriginalIdColumn = relation.model.columnName('originalId')
            // original id links directly to relation
            if (relation.model.columns[modelOriginalIdColumn]) {
                relation.modelIdColumn = modelOriginalIdColumn
                relation.relationIdColumn = modelOriginalIdColumn
            }
            // original id links to relation on default column
            else if (relation.model.columnName(modelOriginalIdColumn)) {
                relation.modelIdColumn = modelOriginalIdColumn
                relation.relationIdColumn = relation.model.columnName(modelOriginalIdColumn)
            }
            // id links directly to relation
            else if (relation.model.columns[modelIdColumn]) {
                relation.modelIdColumn = modelIdColumn
                relation.relationIdColumn = modelIdColumn
            }
            // id links to relation on default column
            else if (relation.model.columnName(modelIdColumn)) {
                relation.modelIdColumn = modelIdColumn
                relation.relationIdColumn = relation.model.columnName(modelIdColumn)
            }
            // relation original id links directly to model
            else if (this.columns[relationOriginalIdColumn]) {
                relation.modelIdColumn = relationOriginalIdColumn
                relation.relationIdColumn = relationOriginalIdColumn
            }
            // relation original id links to model on default column
            else if (this.columnName(relationOriginalIdColumn)) {
                relation.modelIdColumn = this.columnName(relationOriginalIdColumn)
                relation.relationIdColumn = relationOriginalIdColumn
            }
            // relation id links directly to model
            else if (this.columns[relationIdColumn]) {
                relation.modelIdColumn = relationIdColumn
                relation.relationIdColumn = relationIdColumn
            }
            // relation id links to model on default column
            else if (this.columnName(relationIdColumn)) {
                relation.modelIdColumn = this.columnName(relationIdColumn)
                relation.relationIdColumn = relationIdColumn
            }
            // error
            else {
                throw new Error('invalid id column for model '+this.name+' relation '+relatedModelName)
            }
        }
    }
    // return relation
    return this.relations[relatedModelName]
}
1263507
def _to_rest_rels(model, props):
    

    props['to_many'] = {}
    props['to_one'] = {}

    for key in model.to_one:
        try:
            props['to_one'][key] = props.pop(key)
        except KeyError:
            continue

    for key in model.to_many:
        try:
            props['to_many'][key] = props.pop(key)
        except KeyError:
            continue
118047
function(links, resource) {
        var link, association, id, route, relationshipLink, cleanedRoute;

        // Clear the old format
        resource.links = {};

        for (link in links) {
          association = links[link];
          link = Ember.String.camelize(link.split('.').pop());

          if(!association) {
            continue;
          }

          if (typeof association === 'string') {
            if (association.indexOf('/') > -1) {
              route = association;
              id = null;
            } else { // This is no longer valid in JSON API. Potentially remove.
              route = null;
              id = association;
            }
            relationshipLink = null;
          } else {
            if (association.links) {
              relationshipLink =  association.links[this.relationshipKey];
              route = association.links[this.relatedResourceKey];
            }
            id = getLinkageId(association.data);
          }

          if (route) {
            cleanedRoute = this.removeHost(route);
            resource.links[link] = cleanedRoute;

            // Need clarification on how this is used
            if (cleanedRoute.indexOf('{') > -1) {
              DS._routes[link] = cleanedRoute.replace(/^\//, '');
            }
          }
          if (id) {
            resource[link] = id;
          }
        }
        return resource.links;
      }
433120
def retrieve(self, request, *args, **kwargs):
        

        try:
            instance = self.get_object()
            serializer = self.get_serializer(instance)
            return Response(serializer.data)
        except Http404:
            pass

        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
        slug = self.kwargs[lookup_url_kwarg]

        # fall back to accession_temp_fallback
        try:
            tmp = get_object_or_404(
                self.queryset, accession_temp_fallback=slug)
            return HttpResponseRedirect(
                reverse(self.redirect_view_name, (tmp.slug, ))
            )
        except (Http404, FieldError):
            pass

        # fall back to embark ID
        try:
            embark = get_object_or_404(self.queryset, id=int(slug))
            return HttpResponseRedirect(
                reverse(self.redirect_view_name, (embark.slug, ))
            )
        except (Http404, ValueError):
            pass

        # fall back to alt slug
        try:
            from glamkit_collections.utils import alt_slugify
            alt_slug = alt_slugify(slug)
            alt = get_object_or_404(self.queryset, alt_slug=alt_slug)
            return HttpResponseRedirect(
                reverse(self.redirect_view_name, (alt.slug, ))
            )
        except Http404:
            pass

        # well, we tried
        raise Http404
725363
def _parent_queryset(self):
        
        parent = self._resource.parent
        if hasattr(parent, 'view'):
            req = self.request.blank(self.request.path)
            req.registry = self.request.registry
            req.matchdict = {
                parent.id_name: self.request.matchdict.get(parent.id_name)}
            parent_view = parent.view(parent.view._factory, req)
            obj = parent_view.get_item(**req.matchdict)
            if isinstance(self, ItemSubresourceBaseView):
                return
            prop = self._resource.collection_name
            return getattr(obj, prop, None)
1314444
def get_cached_object_or_404(model, timeout=CACHE_TIMEOUT, **kwargs):
    
    try:
        return get_cached_object(model, timeout=timeout, **kwargs)
    except ObjectDoesNotExist, e:
        raise Http404('Reason: %s' % str(e))
692590
def parent(self):
        ''''''

        if not hasattr(self, '_parent'):

            if 'parent' in self.kwargs:

                try:
                    self._parent = Page.objects.get(id=self.kwargs["parent"])
                except Exception as e:
                    raise e
            else:
                if hasattr(self.request, 'leonardo_page'):
                    self._parent = self.request.leonardo_page
                else:
                    return None

        return self._parent
149346
def get(cls, resource_id=None, parent_id=None, grandparent_id=None):
        """""""
        return cls._get(resource_id, parent_id, grandparent_id)
737253
def _find_controller(self, *args):
        '''
        
        '''
        for name in args:
            obj = self._lookup_child(name)
            if obj and iscontroller(obj):
                return obj
        return None
150639
def method_missing(method, *args)
      return self[method] if has_key?(method) # eager loaded with :include
      association_key = :"#{@_resources_key}.#{method}"
      if (polymorphic_association = find_polymorphic_association(self[:links], method))
        attributes = polymorphic_association.last
        ids, type = Array(attributes[:id]), attributes[:type]
        resolved_association_key = :"#{@_resources_key}.#{type.downcase}"
        uri_association_key = "#{association_key}.id"

        extract_resources(ids, resolved_association_key, uri_association_key, *args)
      elsif self[:links] && self[:links].has_key?(method)
        ids = Array(self[:links][method])
        extract_resources(ids, association_key, association_key, *args)
      else
        super
      end
    end
624127
function (req, res) {
        var id = req.params.id;
        {modelName}.findOne({_id: id}, function (err, {name}) {
            if (err) {
                return res.status(500).json({
                    message: 'Error when getting {name}.',
                    error: err
                });
            }
            if (!{name}) {
                return res.status(404).json({
                    message: 'No such {name}'
                });
            }
            return res.json({name});
        });
    }
301798
def get_parent_object(self, parent_queryset=None):
        
        if self._parent_object_cache is not None:
            return self._parent_object_cache

        if parent_queryset is None:
            parent_queryset = self.get_parent_queryset()

        if self.parent_model is None:
            raise ImproperlyConfigured(
                "'%s' must define 'parent_model'" % self.__class__.__name__
            )

        if self.parent_lookup_field is None:
            raise ImproperlyConfigured(
                "'%s' must define 'parent_lookup_field'" % self.__class__.__name__  # noqa
            )

        lookup_url_kwarg = '_'.join([
            self.parent_model_name or self.parent_model._meta.model_name,
            self.parent_lookup_field
        ])

        lookup = self.kwargs.get(lookup_url_kwarg, None)

        if lookup is not None:
            filter_kwargs = {self.parent_lookup_field: lookup}

        else:
            raise ImproperlyConfigured(
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the '
                '`parent_lookup_field` attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
            )

        obj = get_object_or_404(parent_queryset, **filter_kwargs)

        self.check_parent_object_permissions(self.request, obj)
        self._parent_object_cache = obj

        return obj
881937
function(api, parent, modelDefinition, remainingDepth) {
		this.parentAPI = api;
		this.RESTParent = parent;
		this.childModels = [];

		this.remainingDepth = remainingDepth - 1;

		this.model = modelDefinition.model;
		this.modelRouter = Express.Router();

		this.path = this.model.tableName.toLowerCase();
		this.primaryKey = Helpers.getPrimaryKey(this.model);
		this.associatedBy = Helpers.getAssociatedBy(this.RESTParent, this.model);

		this._initializeOptions(modelDefinition);
		this._initializeRoutes(modelDefinition);

		/**
		 * Array of valid columns in the class minus the primary key
		 * However the primary key is only 'not valid' to be set if it is
		 * marked as auto-generated.
		 */
		this.validColumns = _.keys(this.model.rawAttributes);

		if(this.model.rawAttributes[this.primaryKey]._autoGenerated)
			this.validColumns.splice(this.validColumns.indexOf(this.primaryKey), 1);
	}