tags:

views:

33

answers:

1

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?

+1  A: 

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.

istruble
I have many ForeignKey fields that are set to null=True. I'd rather not list them all. But I guess I'll have to.
Luiz C.
You are right again. It does seem like a lot of typing but this is technically a bit of a corner use case. Better than not being able to select_related at all though. Please add your own answer if you come up with something different.
istruble