Model1 has a ForeignKey to Model2. And Model2 has a ForeignKey(Model3, null=True, blank=True) to Model3. By default, when I use select_related() on Model1, Model3 is not selected because of null=True. How can I force select_related() to follow a foreign_key that has has null=True?
The only way I can think of is to explicitly select these foreign keys:
model1s = Model1.objects.all().select_related('model2', 'model2__model3')
Is this the only way?
Yes, that is the way you would go about selecting related items with null=True.
Straight from the docs for select_related:
You can refer to any ForeignKey or OneToOneField relation in the list of fields passed to select_related. Ths includes foreign keys that have null=True (unlike the default select_related() call).
Is there a reason you need a different way to perform this action? If not, you have it right already.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With