开发者

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

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.a开发者_JAVA百科ll().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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜