In Django, Can I `defer()` fields in an object that's being queried by `select_related()`

让人想犯罪 __ 提交于 2019-12-09 10:59:24

问题


In my Django app I want to use select_related() on a QuerySet to "follow" a ForeignKey field, but I only need to access a few of the fields on the "followed" model instance. Can I use the defer() method somehow with my "followed" field.

e.g., if I have...

class BarModel(models.Model):
    ...
    blah = models.TextField()

class FooModel(models.Model):
    bar = models.ForeignKey(BarModel)
    ...    

...and I'm doing FooModel.objects.all().select_related('bar') how can I defer() the field blah.

Thanks.


回答1:


Using Django's double-underscore notation as shown here.

FooModel.objects.all().select_related('bar').defer('bar__blah', ...)


来源:https://stackoverflow.com/questions/5919031/in-django-can-i-defer-fields-in-an-object-thats-being-queried-by-select-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!