Django Query: aggregate() + distinct(fields) not implemented

Viewed 66

I have the following model:

class Data(models.Model):
    metric = models.IntegerField(choices=....)
    date = models.DateField()
    value = models.IntegerField()
    linkedObject = models.ForeignKey()
    .....

What I would like to achieve is to create the sum of all values for the newest metric and date.

What I already use is order_by + distinct to get the newest value for each metric choice. This works.

Data.objects.all().order_by("metric", "-date").distinct("metric")

I tried to combine this with aggregate to make the next step:

Data.objects.all().order_by("metric", "-date").distinct("metric").annotate(Sum("value"))

Unfortunately, I get the following error message:

aggregate() + distinct(fields) not implemented.

Hint: I use postgres as database

1 Answers

This should be possible with:

Data.objects.order_by("metric", "-date").values(
    "metric", "date",
).annotate(value_sum=Sum("value"))

This will group the sum by metric and date and return the result with the desired sorting.

Related