在Django中使用select_related选择特定的字段

时间:2022-02-11 12:28:29

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

我有两个模型文章和博客使用一个外键。在提取文章时,我只想选择blog名称。

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.

生成的查询显示它从Blog模型中选择了所有字段。我尝试使用only()和deferred()与select_related结合,但都没有成功。

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

上面的查询导致了错误:select_related: Choices中的字段名无效

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

如何生成查询,以便只选择文章字段和博客名称?

2 个解决方案

#1


9  

You can use annotate() for this.

您可以为此使用annotate()。

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

#2


6  

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

select_related应该用于整个模型,然后您可以对它进行更多的过滤。这将工作:

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

#1


9  

You can use annotate() for this.

您可以为此使用annotate()。

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

#2


6  

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

select_related应该用于整个模型,然后您可以对它进行更多的过滤。这将工作:

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