Django 选择不同的总和
我有以下(大大简化的)表结构:
Order:
order_number = CharField
order_invoice_number = CharField
order_invoice_value = CharField
多个订单上的发票编号可以相同(订单 O1 的发票编号为 I1,订单 O2 的发票编号为 I1,等等)。所有具有相同发票号码的订单具有相同的发票金额。
例如:
Order no. Invoice no. Value
O1 I1 200
O2 I1 200
O3 I1 200
04 I2 50
05 I3 100
我想做的是对所有发票值进行求和,但不要多次添加具有相同编号的发票。上述项目的总和将为:200+50+100。
我尝试使用
s = orders.values('order_invoice_id').annotate(total=Sum('order_invoice_value')).order_by()
and
s = orders.values('order_invoice_id').order_by().annotate(total=Sum('order_invoice_value'))
执行此操作,但没有得到所需的结果。我从这里的类似问题中尝试了一些不同的解决方案,但无法获得所需的结果。
我无法弄清楚我做错了什么以及我实际上应该做什么才能获得仅使用每个发票值一次的总和。
编辑:
我刚刚意识到在 O5 时我写了 I2 而不是 I3。现在已经写好了。
上述数据的期望结果是每张发票金额的总和,仅使用一次。总和 = I1+I2+I3 = 200+50+100 = 350
I have the following (greatly simplified) table structure:
Order:
order_number = CharField
order_invoice_number = CharField
order_invoice_value = CharField
An invoice number can be identical on more than one order (order O1 has invoice number I1, order O2 has invoice number I1, etc.). All the orders with the same invoice number have the same invoice value.
For example:
Order no. Invoice no. Value
O1 I1 200
O2 I1 200
O3 I1 200
04 I2 50
05 I3 100
What I am trying to do is do a sum over all the invoice values, but don't add the invoices with the same number more than once. The sum for the above items would be: 200+50+100.
I tried doing this using
s = orders.values('order_invoice_id').annotate(total=Sum('order_invoice_value')).order_by()
and
s = orders.values('order_invoice_id').order_by().annotate(total=Sum('order_invoice_value'))
but I didn't get the desired result. I tried a few different solutions from similar questions around here but I couldn't get the desired result.
I can't figure out what I'm doing wrong and what I actually should do to get a sum that uses each invoice value just once.
Edit:
I just realized that at O5 I wrote I2 instead of I3. It's written properly now.
Desired result for the data above is the sum of each invoice value, used only once. Sum = I1+I2+I3 = 200+50+100 = 350
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想说你的模型结构是错误的。您应该有一个订单表,其中包含订单编号和价值,以及一个单独的发票相关表,其中包含从发票到订单的外键。那么你的查询就会很简单。
I would say that your model structure is wrong. You should have one table for Order, containing the order number and value, and a separate related table for the invoices, with a foreign key from Invoice to Order. Then your query would be simple.