Sunday, December 2, 2018

Re: Annotate giving back individual queries rather than results

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





On Sunday, December 2, 2018 at 6:44:21 PM UTC+5:30, Coder Dude wrote:
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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/add4bede-4a98-4124-a2d9-eecfd393763a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment