Python Django查询计数分组依据
我已经读过这篇文章了 我找到了两种实现SQLPython Django查询计数分组依据,python,mysql,django,Python,Mysql,Django,我已经读过这篇文章了 我找到了两种实现SQLcountgroupby的方法 (1)不同的 note_list = Note.objects.filter(user=user).order_by('tag').values('tag').distinct() for note in note_list: print note qs = Note.objects.filter(user=user).annotate(Count('tag')) for e in qs: print
countgroupby
的方法
(1)不同的
note_list = Note.objects.filter(user=user).order_by('tag').values('tag').distinct()
for note in note_list:
print note
qs = Note.objects.filter(user=user).annotate(Count('tag'))
for e in qs:
print e.tag__count
为我工作
(2)注释
note_list = Note.objects.filter(user=user).order_by('tag').values('tag').distinct()
for note in note_list:
print note
qs = Note.objects.filter(user=user).annotate(Count('tag'))
for e in qs:
print e.tag__count
没用<代码>计数始终1
当我使用distinct
而不是order\u by
时,它也不起作用。我试过其他的方法,也没用
django版本:1.8
MySQL版本:5.6.29
更新:
Note.objects.filter(user=user).order_by('tag').values('tag').annotate(count=Count('tag'))
好好为我工作 您应该指定分组字段。在本例中,注释将按标记分组: Note.objects.filter(user=user).values('tag').annotation(Count('id'))
您应该指定要分组的字段。在本例中,注释将按标记分组: Note.objects.filter(user=user).values('tag').annotation(Count('id'))
也许您还没有尝试过,但有另一种方法可以做到这一点,使用.count()方法(e.q.) 这将返回按标记分组的注释的确切数目 我建议您使用POSTGRESQL,而MySQL可以让您更轻松地执行类似操作:
Note.objects.filter(user=user).distinct('tag').count()
也许您还没有尝试过,但有另一种方法可以做到这一点,使用.count()方法(e.q.) 这将返回按标记分组的注释的确切数目 我建议您使用POSTGRESQL,而MySQL可以让您更轻松地执行类似操作:
Note.objects.filter(user=user).distinct('tag').count()
Note.objects.filter(user=user)、value('tag')、annotate(Count('tag'))
我以前试过,效果不好。Note.objects.filter(user=user)、value('tag')、annotate(Count('tag'))
我以前试过,效果不好。