Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Annotating multiple Sum() object gives wrong result

models.py looks like this

class Channel(Model):
    name = CharField()

class Contract(Model):
    channel = ForeignKey(Channel, related_name='contracts')
    fee = IntegerField()

class ContractPayment(Model):
    contract = ForeignKey(Contract, related_name='payments')
    value = IntegerField()

When I query a model:

Channel.objects.annotate(pay=Sum('contracts__fee'))

It returns: 75000. And Its correct but when I query like this:

Channel.objects.annotate(pay=Sum('contracts__fee'))
               .annotate(paid=Sum('contracts__payments__value'))


And it returns: pay: 96000, paid: 33000. As you can see the pay is changed. What is going on here? I read the ticket #10060 but no luck.

like image 855
kyore Avatar asked Aug 16 '26 06:08

kyore


1 Answers

I think you have to use distinct=True in annotate() as below...

Channel.objects.annotate(pay=Sum('contracts__fee', distinct=True)).annotate(paid=Sum('contracts__payments__value', distinct=True))
like image 77
MK Patel Avatar answered Aug 17 '26 20:08

MK Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!