Django 推迟相关模型查询集中的所有字段

django deferring all fields in a related model queryset

我有一个查询需要第二个相关模型 Model1.objects.all().select_related("model2__model3")

但我不需要 model2 的任何字段,只需要 model3 的许多不同字段,例如obj.model2.model3.name 和其他人

如何在不逐一明确提及的情况下推迟 model2 中的所有字段?

编辑:模型 1 具有指向模型 2 的外键,模型 2 具有指向模型 3 的外键

我相信您正在尝试使用 .only() 查询集方法,下面的代码片段应该有效。

根据 django 文档:

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")

使用上面的代码片段,尝试访问 model2 中的任何字段将导致数据库访问,而访问 model2.model3.name 则不会。

这样 model2 中的所有字段都将被推迟。如果你想访问另一个字段,只需将它传递给 .only() 函数 .only('model2__model3__name', 'model2__model3__another').