tisuchi
December 2017
M T W T F S S
« Nov    
 123
45678910
11121314151617
18192021222324
25262728293031

Categories


How to query as GROUP BY in django?

tisuchitisuchi

If you are facing how to write query as Group By in django, this post might be helpful for you.

Imagine that, you want to write query like this way.

SELECT userid, COUNT(userid) AS ucount
FROM members GROUP BY userid

Now, in your view’s function, add-

//import library from django to count record
from django.db.models import Count
Messages.objects.values('userid').annotate(ucount=Count('userid'))

Now in you may get result like this way.

[{'userid': 2909, 'ucount': 11}, 
{'userid': 8749, 'ucount': 30}]

You can iterate now.

<p>I speak PHP, Laravel, MySql, JavaScript, VueJS, Python, Bengali and English. I am originated from Bangladesh, currently working in Malaysia. My day time job is to develop web apps for EDV Standard, and night time, I solve coding issues for communities.</p>

Comments 0
There are currently no comments.