Alexander
Alexander

Reputation: 727

Django perform a join on multiple tables

I have the following tables:

class A: 
    field_1 = models.CharField()
    field_2 = models.IntegerField()

class B: 
    a = models.ForeignKey(A, related_name='table_b')
    some_other_field = models.CharField()

class C: 
    b = models.ForeignKey(B, related_name="table_c")
    other_field = models.CharField()

Let's assume ids are provided for objects on table A, I need to get all the C objects that are related to table A through table B. I have the following query, which gives me what I need but I am wondering if there is a better way to do this, I was reading into prefetch_related and select_related but can't wrap my head around on how to use them so far:

c_list = C.objects.filter(b__in=B.objects.filter(a__pk__in=table_a_ids))

Also, I would like to group them by other_field.

Upvotes: 1

Views: 326

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

No need for .select_related(…) or .prefetch_related(…). You can filter with:

c_list = C.objects.filter(b__a_id__in=table_a_ids)

Upvotes: 1

Related Questions