Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django查询计数分组依据_Python_Mysql_Django - Fatal编程技术网

Python Django查询计数分组依据

Python 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

我已经读过这篇文章了

我找到了两种实现SQL
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'))
我以前试过,效果不好。