Search code examples
phpdjangodjango-queryset

django deferring all fields in a related model queryset


I have a query where I need the second related model Model1.objects.all().select_related("model2__model3")

but I don't need any field from model2, only many different fields from model3, e.g. obj.model2.model3.name and others

How can I defer all fields from model2 without explicitly mentioning them one after the other?

EDIT: Model1 has ForeignKey to Model2 that has ForeignKey to Model3


Solution

  • I believe that you're trying to use the .only() queryset method, the below snippet should work.

    As per the django docs:

    The only() method is more or less the opposite of defer(). You call it with the fields that should not be deferred when retrieving a model. If you have a model where almost all the fields need to be deferred, using only() to specify the complementary set of fields can result in simpler code.

    Model1.objects.all().only('model2__model3__name').select_related("model2__model3")
    

    With the above snippet, trying to access any field from model2 will result in a database access, whilst accessing model2.model3.name will not.

    This way all fields from model2 will be deferred. And if you want to access another field just pass it to the .only() function .only('model2__model3__name', 'model2__model3__another').