0

Consider the following definitions:

class A(models.Model):
    ...

class B(models.Model):
    a_obs = models.ForeignKey(A, related_name='b')

class C(models.Model):
    b_obs = models.ForeignKey(B, related_name='c')

let's say we have an instance ob1 of type A. How could I do a double reverse lookup in order to obtain all C instances related to ob1 without using the C.objects nor the B.objects managers?

Normally doing ob1.b.all() will give me a QuerySet of B's, but what then?

andreihondrari
  • 5,743
  • 5
  • 30
  • 59
  • Why can't you use `C.objects` or `B.objects`? – mipadi Jan 22 '15 at 20:10
  • @mipadi because of circular imports. – andreihondrari Jan 22 '15 at 20:11
  • Why not fix or deal with the circular import? – mipadi Jan 22 '15 at 20:11
  • In worst case scenario I will but I would also be interested to see if such a lookup is possible. – andreihondrari Jan 22 '15 at 20:12
  • A more dire concern than circular imports (which can often be dealt with by using the class names in string literals in FK field definitions) is IMHO readability and comprehensibility. Thus I've asked a [new question](http://stackoverflow.com/questions/36866755/chained-reverse-lookups-in-django-but-without-following-the-forward-relations) explicitly about following the reverse direction. – das-g Apr 26 '16 at 13:53

1 Answers1

0

Doing "double reverse lookup" costs a lot of resources. Are you sure data can't be structured any other way?

To answer your question I found solution here that might fit your requirements. Try doing:

# You start with object A as objA
objsB = objA.b.all()
requested_c_objects = [C.objects.filter(b_obs=b) for b in objsB]

I haven't tested it so it may contains errors, but hope you get the idea.

P.S.: Without *.objects is not possible doing it. Try adding your own Manager methods or do it in SQL syntax directly.

Community
  • 1
  • 1
gcerar
  • 920
  • 1
  • 13
  • 24