Search code examples
djangodjango-orm

Select Objects related in third table


Say I have the models

class A(models.Model):

class B(models.Model):
   
class C(models.model):
    b = models.ForeignKey(B)

class D(models.Model):
    c = models.ForeignKey(C)
    a = models.ForeignKey(A)

What would a ORM query look like to select all Bs that are related to C's that are related to a specific A through table D?


Solution

  • As mentioned by the comment on your post you can use the autogenerated related name. But it never hurts to set it yourself.

    class C(models.model):
        b = models.ForeignKey(B, related_name="c")
    
    class D(models.Model):
        c = models.ForeignKey(C, related_name="d")
        a = models.ForeignKey(A, related_name="d")
    
    

    Then:

    B.objects.filter(c__d__a=specific_a_obj).distinct()