1

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.
3
  • How would you know which values to cosider (from the set of task with identical data)? Commented Mar 11, 2015 at 19:44
  • Do you need inline queryset answer ? Commented Mar 11, 2015 at 19:47
  • @LudwikTrammer: So u mean to say we cannot achieve this in a single query? DO we need to write 2 queries? Commented Mar 11, 2015 at 19:49

1 Answer 1

1

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"})
Sign up to request clarification or add additional context in comments.

3 Comments

But values will not return me the whole object right? I am trying to get the entire object. Is there a way to do that?
@RogerFederer will returns only data attribute.
@RogerFederer, checkout my second example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.