为什么注释会生成重复项? [英] Why annotate generates duplicate entries?

查看:120
本文介绍了为什么注释会生成重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

payments = Payment.objects.filter(
        customer=self.customer,
        created_at__gte=kwargs['start_date'],
        created_at__lte=kwargs['end_date']
    ).order_by('-date')

balance = payments.values('currency').annotate(Sum('amount'))

> print(balance)
> [{'amount__sum': Decimal('0.00'), 'currency': 'USD'},
   {'amount__sum': Decimal('0.00'), 'currency': 'USD'},
   {'amount__sum': Decimal('9000.00'), 'currency': 'SEK'},
   {'amount__sum': Decimal('45000.00'), 'currency': 'EUR'},
   {'amount__sum': Decimal('11385.00'), 'currency': 'SEK'}]

此客户的付款清单:

> print(payments)
> ('-1487.50', 'USD')
('1487.50', 'USD')
('-3663.72', 'USD')
('3663.72', 'USD')
('15000.00', 'EUR')
('9000.00', 'SEK')
('30000.00', 'EUR')
('9865.00', 'SEK')
('1520.00', 'SEK')

如果我使用汇总,得到总和,但是对于所有货币,这不是我想要的。我必须能够分解成货币。

If I use aggregate, I get the Sum, but for all currencies and that's not what I want. I must be able to split into currencies.

{'amount__sum': Decimal('65385.00')}

我正在尝试通过按客户分组并按货币求和来提取付款。但是,发生的是,它没有对某些值求和,而是将它们重复。有任何想法吗?

I am trying to extract the payments by customer grouping and summing by currencies. However what happens is that it doesn't Sum some of the values instead duplicating them. Any ideas?

推荐答案

导致此问题的是 order_by order_by 中提到的字段将隐含地属于该组,否则根据values 中提到的字段。 href = https://docs.djangoproject.com/es/1.9/topics/db/aggregation/#interaction-with-default-ordering-or-order-by rel = nofollow>有关聚合和order_by 。

It is the order_by that causes this. Fields mentioned in order_by will implicitly be part of the group otherwise defined as the fields mentioned in values according to the docs on aggregation and order_by.

查看是否

Payment.objects.filter(
        customer=self.customer,
        created_at__gte=kwargs['start_date'],
        created_at__lte=kwargs['end_date']
    ).values('currency').annotate(Sum('amount'))

不会为您提供您所要的确切答案。

won't give you exactly the answer you are looking for.

这也是由 Payment.Meta.ordering 上的默认顺序设置引起的。如果这样做,则需要像这样明确取消订单:

This will also be caused by a default ordering set on Payment.Meta.ordering. If you did that you will need to cancel out the ordering explicitly like so:

Payment.objects.filter(
        customer=self.customer,
        created_at__gte=kwargs['start_date'],
        created_at__lte=kwargs['end_date']
    ).order_by().values('currency').annotate(Sum('amount'))

这篇关于为什么注释会生成重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆