在Django中使用select_related选择特定字段 [英] Selecting specific fields using select_related in Django

查看:381
本文介绍了在Django中使用select_related选择特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

生成的查询表明它从Blog模型中选择了所有字段。
我尝试将only()和defer()与select_related一起使用,但都没有解决。

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

上述查询导致错误:select_related中给出的无效字段名称:选择为:Blog

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?

推荐答案

您可以使用 annotate()

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

这篇关于在Django中使用select_related选择特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆