Annotate giving back individual queries rather than results

17 views
Skip to first unread message

Coder Dude

unread,
Dec 2, 2018, 8:14:21 AM12/2/18
to Django users
Here are my models:
from django.contrib.auth.models import User as DefaultUser
class Submission(models.Model):
user = models.ForeignKey(to=DefaultUser,
on_delete=models.CASCADE
)
total_score = models.DecimalField()


The query that I am trying is :
Submission.objects.values('user').annotate(Count('id'))

I want to get the count of Submissions for each user

But this returns me set of individual submission with count as 1

Output:
{'user': 1, 'id__count': 1}
{'user': 1, 'id__count': 1}
{'user': 1, 'id__count': 1}
{'user': 1, 'id__count': 1}
{'user': 2, 'id__count': 1}
{'user': 2, 'id__count': 1}
{'user': 3, 'id__count': 1}

Whereas the output that I want is:
{'user': 1, 'id__count': 4}
{'user': 2, 'id__count': 2}
{'user': 3, 'id__count': 1}

What am I doing wrong?
Please help

Coder Dude

unread,
Dec 2, 2018, 8:51:17 AM12/2/18
to Django users
Solved It.
It seems as of django 2.1, we need to add another parameter order_by

Submission.objects.values('user').annotate(Count('id')).order_by('user')

documentation

Thanks

Simon Charette

unread,
Dec 2, 2018, 3:52:33 PM12/2/18
to Django users
Hey there,

I just wanted to clarify that the behavior of including the Meta.ordering
fields in aggregation grouping been around for a while and Django 2.2
deprecates it to deal with the exact type of confusion you experienced here.

Best,
Simon
Reply all
Reply to author
Forward
0 new messages