使用 Django 的查询集进行分组

发布于 2025-01-13 00:12:54 字数 1124 浏览 2 评论 0原文

我在 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 -

enter image description here

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 -

enter image description here

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感性 2025-01-20 00:12:54

发生这种情况是因为 .values 中有 id,并且根据底层查询,它按 idbuy_price_per_unit 进行分组代码>两者。

因此,只需从 .values 中删除 id

orders = Orders.objects.values('buy_price_per_unit')\
        .annotate(units=Sum("units"))\
        .order_by("-buy_price_per_unit")\

This is happening because you have id in .values and based on the underlying query, it is grouping on id and buy_price_per_unit both.

So simply remove id from .values

orders = Orders.objects.values('buy_price_per_unit')\
        .annotate(units=Sum("units"))\
        .order_by("-buy_price_per_unit")\
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文