Django values_list 与值 [英] Django values_list vs values
问题描述
在Django中,以下两者有什么区别:
In Django, what's the difference between the following two:
Article.objects.values_list('comment_id', flat=True).distinct()
对比
Article.objects.values('comment_id').distinct()
我的目标是在每个 Article
下获得一个唯一评论 ID 的列表.我已经阅读了文档(实际上已经使用了这两种方法).结果看起来很相似.
My goal is to get a list of unique comment ids under each Article
. I've read the documentation (and in fact have used both approaches). The results overtly seem similar.
推荐答案
values()
方法返回一个包含字典的查询集:
The values()
method returns a QuerySet containing dictionaries:
<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>
values_list()
方法返回一个包含元组的 QuerySet:
The values_list()
method returns a QuerySet containing tuples:
<QuerySet [(1,), (2,)]>
如果您将 values_list()
与单个字段一起使用,您可以使用 flat=True
返回单个值的 QuerySet 而不是 1 元组:>
If you are using values_list()
with a single field, you can use flat=True
to return a QuerySet of single values instead of 1-tuples:
<QuerySet [1, 2]>
这篇关于Django values_list 与值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!