How To Do A Proper Groupby Query In Django
I have a table that holds multiple tracking id's in it. What I'm trying to do is group all tracking id's and get a count for them. This is what the SQL query would look like: SELEC
Solution 1:
How about (partially inspired by @second's answer):
users = Tracking.objects.values( 'tracking_id' ).annotate(dcount=Count('tracking_id'))
and then
foruserin users:
stats.append((user[ 'tracking_id' ], user[ 'dcount' ]))
?
Solution 2:
for times like this, I would recommend trying out your code in a shell
./manage.py shell
opens a python shell with your project code in the system path
>>> from myapp.models import Tracking
>>> from django.db.models import Count
>>> Tracking.objects.values('tracking_id').annotate(dcount=Count('tracking_id'))
[{'tracking_id': 53, 'dcount': 12}, {'tracking_id': 1, 'dcount': 32}, ...]
this lets you see the format of the returned data and get you on your way
alternatively, you can add a pdb (python debugger) statement in your view code, (assuming runserver
is serving your code), and load the page. when the pdb statement is reached, your server will stop and drop you into a debugger shell, right in the context of your view
defview(request):
[...]
import pdb; pdb.set_trace # or even better, pip install ipdb and use insteadreturn"foo"
Post a Comment for "How To Do A Proper Groupby Query In Django"