> On May 22, 12:51 pm, sk <6b656...@gmail.com> wrote:
>
>
>
>
>
> > If I have a hierarchy of models such that:
>
> > class A(models.Model):
> >     name = CharField(max_length=10)
>
> > class B(models.Model):
> >     name = CharField(max_length=10)
> >     a= ForeignKey(A)
>
> > class C(models.Model):
> >     name = CharField(max_length=10)
> >     b= ForeignKey(B)
>
> > If I have an instance of C, as returned by:
>
> > c = C.objects.get(pk=1)
>
> > How do I get the name of A?
>
> > I realise I can go via B, but I am hoping to be able to follow the
> > chain back to A from any arbitrary point in (a much longer) chain.
>
> > For example:
> > If this was repeated up to F in an identical manner.
> > If I pass a function any instance from A to F I would want to return
> > A.name.
>
> > I am sure there must be a simple way to get the root data, but I am
> > having trouble finding it.
>
> You really do have to go through the relations through the chain -
> there is no direct links from C to A so it is impossible to just hop
> from C to A.
>
> You can query the A instance by something like
> A.objects.filter(pk=B.objects.filter(pk=c.b_id)) - this should return
> the A instance in one query. (It might be you will need to use
> pk__in).
>
> Or, you could use select_related or prefetch_related to do the
> fetching.
>
>  - Anssi- Hide quoted text -
>
> - Show quoted text -

Fair enough, thank you for your reply.

I is it posible to 'follow the chain' without knowing the exact
instance you are in? for example can i get all foreign keys for a
given instance, then follow them? To be honest this is just for
interest now - I have implemented this with some hard-coding of how to
decide where you are in the 'tree'.

Many thanks
Stephen

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to