blue note
blue note

Reputation: 29071

Django: join two table on foreign key to third table?

I have three models

class A(Model):
    ...

class B(Model):
    id = IntegerField()
    a = ForeignKey(A)

class C(Model):
    id = IntegerField()
    a = ForeignKey(A)

I want get the pairs of (B.id, C.id), for which B.a==C.a. How do I make that join using the django orm?

Upvotes: 2

Views: 374

Answers (1)

2ps
2ps

Reputation: 15926

Django allows you to reverse the lookup in much the same way that you can use do a forward lookup using __:

It works backwards, too. To refer to a “reverse” relationship, just use the lowercase name of the model.

This example retrieves all Blog objects which have at least one Entry whose headline contains 'Lennon':

Blog.objects.filter(entry__headline__contains='Lennon')

I think you can do something like this, with @Daniel Roseman's caveat about the type of result set that you will get back.

ids = B.objects.prefetch_related('a', 'a__c').values_list('id', 'a__c__id')

The prefetch related will help with performance in older versions of django if memory serves.

Upvotes: 3

Related Questions