Django GROUP BY字段值 [英] Django GROUP BY field value
问题描述
令人惊讶的是,我找不到通过查询进行分组的方法。
Surprising that I could not find a way to make a group by query.
我有一个查询集 qs
,并且考虑到 qs
排除了 some_prop.val
分组> some_prop 是 None
。
I have a query set qs
and I am trying to group by some_prop.val
, considering qs
is excluding entries where some_prop
is None
.
假设值是 [1、2、3]
,那么我就会得到这样的结果:
Let's say the values are [1, 2, 3]
, then I would be after a result like this:
{1: entries1, 2: entries2, 3: entries3}
Django ORM是否提供任何功能来分组结果是这样的吗?
Does the Django ORM provide any feature to group results like this?
推荐答案
(据我所知)没有特定的Django ORM方式,但是您可以以下是获得按字段值分组的条目字典的方法:
There is not a specific Django ORM way (as far as I know) but you can do the following to get a dictionary of entries grouped by values of a field:
-
使用
.values_list()
与flat = True
获取数据中现有值的列表基础(如果您事先不了解它们)。还可以使用.distinct()
消除重复的值,因为我们不在乎那些值:
Use
.values_list()
withflat=True
to get a list of the existent values in your database (if you don't know them beforehand). Also use.distinct()
to elimintae duplicate values as we do not care for those:
value_list = MyModel.objects.values_list(
'interesting_field', flat=True
).distinct()
现在遍历 value_list
并填写您的字典:
group_by_value = {}
for value in value_list:
group_by_value[value] = MyModel.objects.filter(interesting_field=value)
现在 group_by_value
字典包含 interesting_field
中不同的值作为键,并包含queryset对象的值,每个对象都包含 MyModel
中带有 interesting_field = value_list中的值
。
Now group_by_value
dictionary contains as keys the distinct values in your interesting_field
and as values the queryset objects, each containing the entries of MyModel
with interesting_field=a value from value_list
.
出于遗留评论的原因而将其保留在此处。
我做了一个 Q& A样式示例,其中模拟了 COUNT ... GROUP BY
SQL查询。
I have made a Q&A style example in, which simulates a COUNT ... GROUP BY
SQL query.
本质上,您需要使用 .order_by
进行分组和 。 annotate()
依靠模型的 .values()
。
Essentially you need to utilize the .order_by
for grouping and the .annotate()
to count on the model's .values()
.
以下是上述示例:
我们可以在Django ORM上执行
COUNT ... GROUP BY
个SQL等效查询,并使用annotate()
,values()
,order_by()
和
dj ango.db.models
的Count
方法:
We can perform a
COUNT ... GROUP BY
SQL equivalent query on Django ORM, with the use ofannotate()
,values()
,order_by()
and thedjango.db.models
'sCount
methods:
让我们的模型为:
class Books(models.Model):
title = models.CharField()
author = models.CharField()
让我们假设我们要计算每个不同作者中有多少本书对象图书表:
Lets assume that we want to count how many book objects per distinct author exist in our Book table:
result = Books.objects.values('author')
.order_by('author')
.annotate(count=Count('author'))
现在的结果包含一个查询集有两列:作者和计数:
Now result contains a queryset with two columns: author and count:
author | count
------------|-------
OneAuthor | 5
OtherAuthor | 2
... | ...
这篇关于Django GROUP BY字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!