Returning data belonging to a model (FK)

22 views
Skip to first unread message

David

unread,
Jul 27, 2012, 8:47:37 AM7/27/12
to django...@googlegroups.com
Hi

I am trying to abstract one of my applications.

        for f in self._meta.fields:
            print f
            if f.get_internal_type() == "ForeignKey":
                for o in f.related.parent_model.objects.all():

I am using the above code to isolate any fields in self._meta.fields that are foreign keys. I need to get data from these foreignkey relations to other models.

Is this possible please?

Thank you

Victor Rocha

unread,
Jul 27, 2012, 9:14:35 AM7/27/12
to django...@googlegroups.com
David,

Django already comes with a built-in contenttypes application which does exactly what you trying to accomplish, i think.

You should read the documentation:

David

unread,
Jul 27, 2012, 9:20:07 AM7/27/12
to django...@googlegroups.com
Hi Victor

I am using contenttypes already and am finding it hugely useful. I am trying to decouple the applications need to "know" the model that the contenttype has linked to. This way it should generically understand, interpret and perform functions on any given instance of an object regardless of contenttype.

Hope that makes sense.

Melvyn Sopacua

unread,
Aug 2, 2012, 4:10:22 PM8/2/12
to django...@googlegroups.com
On 27-7-2012 14:47, David wrote:

> I am using the above code to isolate any fields in self._meta.fields that
> are foreign keys. I need to get data from these foreignkey relations to
> other models.
>
> Is this possible please?

Depends what you need to do with it. I'm doing something similar for my
JSONResponseMixin and recursively visit foreign keys. However, since
models are converted to dictionaries by this method, I just tack on the
result as a another dict, so for a city model you'd get:
{
'name': 'Amsterdam',
'country': { 'name': 'Netherlands', 'code': 'NL' }
}

The principle applies though, you can fetch the fields you want and tack
on the result on whatever object instance you want to tack it on that
you have access to. You can't however tack it on to classes, or at least
I'm not seeing an easy way to do that.

--
Melvyn Sopacua
Reply all
Reply to author
Forward
0 new messages