Selecting specific fields using select_related in Django

落花浮王杯 提交于 2019-12-21 06:50:57

问题


I have two models Article and Blog related using a foreign key. I want to select only blog name while extracting the article.

articles = Articles.objects.all().select_related('blog__name')

The query generated shows that it selected all the fields from the Blog model. I tried using only() and defer() with select_related but both didn't work out.

articles = Articles.objects.all().select_related('blog__name').only('blog__name', 'title', 'create_time')

The above query resulted in error: Invalid field name(s) given in select_related: Choices are: blog

How do i generate a query so that only article fields and blog name is selected?


回答1:


You can use annotate() for this.

>>> a = Articles.objects.annotate(blog_name=F('blog__name')).first()
>>> a.title
>>> a.blog_name



回答2:


select_related should be use on the whole model, and then you can filter it more. This will work:

Articles.objects.select_related('blog').only('blog__name', 'title', 'create_time')


来源:https://stackoverflow.com/questions/35524259/selecting-specific-fields-using-select-related-in-django

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