使用 Django 的查询集进行分组
我在 Django 中有一个模型,这就是它的样子,字段较少 -
我想将行按 buy_price_per_unit
进行分组,同时我也想知道总单位数该 buy_price_per_unit
正在出售。
因此,在我们的例子中,只有两个不同的 buy_price_per_unit
可用 (9, 10)
。因此,查询将仅返回两行,如下所示 -
我必须满足的最后一个条件是查询结果应按 buy_price_per_unit
的降序排列。
这是我到目前为止所尝试的 -
orders = Orders.objects.values('id', 'buy_price_per_unit')\
.annotate(units=Sum("units"))\
.order_by("-buy_price_per_unit")\
上面查询的响应是 -
[
{
"id": 13,
"buy_price_per_unit": 10,
"units": 1
},
{
"id": 12,
"buy_price_per_unit": 9,
"units": 10
},
{
"id": 14,
"buy_price_per_unit": 9,
"units": 2
},
{
"id": 15,
"buy_price_per_unit": 9,
"units": 1
}
]
该响应的问题是,即使价格相同,也会返回多个记录。
I have a model in Django and this is how it looks like with fewer fields -
I want to group the rows w.r.t buy_price_per_unit
and at the same time I also want to know the total units on sale for that buy_price_per_unit
.
So in our case only two distinct buy_price_per_unit
are available (9, 10)
. Hence the query would return only two rows like this -
The one last condition which I have to meet is the query result should be in descending order of buy_price_per_unit
.
This is what I have tried so far -
orders = Orders.objects.values('id', 'buy_price_per_unit')\
.annotate(units=Sum("units"))\
.order_by("-buy_price_per_unit")\
The response for the query above was -
[
{
"id": 13,
"buy_price_per_unit": 10,
"units": 1
},
{
"id": 12,
"buy_price_per_unit": 9,
"units": 10
},
{
"id": 14,
"buy_price_per_unit": 9,
"units": 2
},
{
"id": 15,
"buy_price_per_unit": 9,
"units": 1
}
]
The problem with this response is that even for the same price multiple records are being returned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
发生这种情况是因为
.values
中有id
,并且根据底层查询,它按id
和buy_price_per_unit
进行分组代码>两者。因此,只需从
.values
中删除id
This is happening because you have
id
in.values
and based on the underlying query, it is grouping onid
andbuy_price_per_unit
both.So simply remove
id
from.values