如何在django中进行适当的groupby查询 [英] How to do a proper groupby query in django
本文介绍了如何在django中进行适当的groupby查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是SQL查询的样子:
SELECT tracking_id,COUNT(*)
/ pre>
FROM tracking
GROUP BY tracking_id
我想我已经找到了在django中执行此操作的正确方法,但是我缺少某些东西,目前正在收到错误
异常值:'dict'对象没有属性'tracking_id'
这是我的看法:
def stats(request):
users = Tracking.objects.values('tracking_id')。annotate(dcount = Count('tracking_id '))
stats = []
用户用户:
stats.append((user.tracking_id,user.dcount))
return render_to_response('tracking / stats.html',{'stats':stats,})
任何帮助将不胜感激!
解决方案如何(部分来自@ second's answer):
users = Tracking.objects。值('tracking_id').annotate(dcount = Count('tracking_id'))
然后
为用户的用户:
stats.append((user ['tracking_id'],user ['dcount'] ))
?
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:
SELECT tracking_id, COUNT( * ) FROM tracking GROUP BY tracking_id
I think I've found the correct method of doing this in django however I'm missing something and am currently getting the error
Exception Value: 'dict' object has no attribute 'tracking_id'
Here's what my view looks like:
def stats(request): users = Tracking.objects.values('tracking_id').annotate(dcount=Count('tracking_id')) stats = [] for user in users: stats.append((user.tracking_id, user.dcount)) return render_to_response('tracking/stats.html', { 'stats': stats, })
Any help would be appreciated!
解决方案How about (partially inspired by @second's answer):
users = Tracking.objects.values( 'tracking_id' ).annotate(dcount=Count('tracking_id'))
and then
for user in users: stats.append((user[ 'tracking_id' ], user[ 'dcount' ]))
?
这篇关于如何在django中进行适当的groupby查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文