按2个字段组合分组,然后按每个组的和排序,多个注解django

gc0ot86w  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(273)

我试图从发票中获得按利润总额排序的顶级产品,如下所示:
按给定筛选发票 store_id 分组依据 product_name 然后得到 Sumgross_margin 每组的
最后点了 Sumgross_margin (从高到低)
以前的代码错误:

high_margin = StoreInvoiceBreakup.objects \
  .filter(store_invoice__store_id=store_id) \   
  .annotate(product_count=Count('product_name')) \
  .annotate(gross_margin_sum=Sum('gross_margin')) \
  .order_by('-gross_margin_sum') \
  .values(name=F('product_name')) \
  .distinct()[:int(top_count)]

然后通过堆栈溢出解决了多个注解问题类似于:
(因为以前的代码给出了错误的结果。)
新的正确代码:

high_margin = StoreInvoiceBreakup.objects \
  .filter(store_invoice__store_id=store_id) \
  .values('product_name') \
  .annotate(gross_margin_sum=Sum('gross_margin')) \
  .order_by('gross_margin_sum') \
  .distinct()[:int(sell_range)]

输出结果如下:

"high_margin ": [{
  "product_name": "ABCD",
  "gross_margin_sum": 100  --sum of all margins for abcd
}...other products with sum]

这是绝对的 correct ,但遇到了另一个问题,如:
一个商店可以有一个同样的产品 product_name ,但可能有不同的到期日。
所以我想要的是,
按产品类别分组 product_name 以及 expiry_date 组合。
那就去拿 margin 每个组的总和和 Sum ,具有不同的组合(不只是不同的产品名称。)

  • 删除distinct没有帮助

或者通过 cursor 这样做也会有帮助。如果不能通过queryset和docs完成。
发票明细数据如下所示:

name  | margin  | ... | total | tax | etc..
  abcd  | 50      | ... |
  abcd  | 50      | ... |
  abcd  | 15      | ... |
  abcd  | 15      | ... |

输出如下:

"high_margin ": [{
  "product_name": "ABCD",
  "gross_margin_sum": 100  --sum for 2018 and abcd
  "expiry_date": 2018
},
{
  "product_name": "ABCD",
  "gross_margin_sum": 30  --sum for 2017 and abcd
  "expiry_date": 2017
},... other products with sum and expiry_date]

这些产品看起来像:

name  |  expiry_date  | size | price | etc...
  abcd  |  2018         |
  abcd  |  2017         |
  xyz   |  2019         |
  pqrs  |  2017         |

保证金只存在于发票中,不存在于店内产品中。
出口日期仅存在于商店产品中,不存在于发票中
我还希望能够更改最终输出名称。 Invoice_product 通过Map foreign_keystore_product_mapping ,然后Map到 master_product .
sql查询可能如下所示:

SELECT NAME, EXPIRY_DATE, SUM(GROSS_MARGIN)
FROM INVOICE_BREAKUP GROUP BY NAME, EXPIRY_DATE
WHERE STORE_ID = 1

  • 不是实际流量
ac1kyiln

ac1kyiln1#

print(str(high_margin.query))

这样你就能得到 queryset 产生和播放作为一个懒惰的查询,如这里的答案所述。所以我通过添加 expiry_datevalues ,它按名称生成组,过期日期由文档指定。
代码更改为:

high_margin = StoreInvoiceBreakup.objects \
  .filter(store_invoice__store_id=store_id) \
  .values('product_name', 'expiry_date') \
  .annotate(gross_margin_sum=Sum('gross_margin')) \
  .order_by('gross_margin_sum') \
  .distinct()[:int(sell_range)]
  • 不确定是否正确

相关问题