Django: select_related to a table vs table's field

392 views Asked by At

I have 2 models

class A(models.Model):
    val = models.IntegerField()

class B(models.Model):
    val2 = models.IntegerField()
    a = models.ForeignKey(A)

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

How is the query -

C.objects.select_related('B').all()

better than -

C.objects.select_related('B__val2').all()

And if not how query one can be optimised?

1

There are 1 answers

1
AudioBubble On

Try to filter model you need, by lowcase filter of the child models

B.objects.filter(c__isnull=False)

read more here lookups-that-span-relationships