Abhishek
Abhishek

Reputation: 3066

Django annotate on another distinct field in queryset

I have a model as follows:

class Task(models.Model):
    value= models.IntegerField()
    data = models.CharField(max_length=50, blank=True)

I want to make a query to return the sum of the values for every distinct data. I tried the following but it didn't work:

Task.objects.all().distinct('data').annotate(value = Sum('value'))

I was getting this error:

NotImplementedError: annotate() + distinct(fields) not implemented.

Upvotes: 1

Views: 2183

Answers (1)

Todor
Todor

Reputation: 16050

Try with values instead of distinct, this will group by data (not sure if this is what you need).

Task.objects.values('data').annotate(Sum('value'))

An attempt with .extra (to select the entire object)

Task.objects.extra(select={'values_sum': "SELECT SUM(values) FROM myapp_task t WHERE t.data = myapp_task.data"})

Upvotes: 1

Related Questions