Distinct values with multiple Sum aggregations on reverse relation

Viewed 1208

According to the Django docs combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries. They furthermore note, that Count has a distinct parameter that may help.

Is there something similiar to Sum? I end up with wrong results in this stripped down example. The resulting amount values are too high for most projects.

qs = Client.filter('project__date__year=2017').annotate(
    isum=Sum('project__intoffer__amount', distinct=True),
    esum=Sum('project__extoffer__amount', distinct=True)
)

The distinct=True parameters don't make any difference.

Simplified models.py:

class Client(models.Model):
    title = models.CharField('Title', max_length=50)

class Project(models.Model):
    title = models.CharField('Title', max_length=100)
    client = models.ForeignKey('Client', verbose_name='Client')
    date = models.DateField('Date', blank=True, null=True)

class IntOffer(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    amount = models.DecimalField('Amount', max_digits=19, decimal_places=2)

class ExtOffer(models.Model):
    project = models.ForeignKey(Project, verbose_name='Project')
    amount = models.DecimalField('Amount', max_digits=19, decimal_places=2)
1 Answers
Related