Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force select_related() to select ForeignKeys that have null=True attribute?

Tags:

django

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?

like image 571
Luiz C. Avatar asked Mar 04 '10 14:03

Luiz C.


1 Answers

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.

like image 120
istruble Avatar answered Sep 18 '22 12:09

istruble