我正在计算 django 模型中具有重复值的行数,但遇到了一些小问题。 我看过这个问题Django Select Rows with duplicate Values
解决方案是完美的。但我的问题是,如果我想对行进行计数并根据以下条件进行分组:重复行的名称以及重复的次数,而不是仅显示重复行的名称,该怎么办行。
到目前为止我的代码:
views.py
dupes = Application.objects.values('school_name').annotate(Count('id')).filter(id__count__gt=1)
query = Application.objects.filter(school_name__in=[item['school_name'] for item in dupes])
query 变量返回一个查询集,其中包含字段 school_name 具有重复值的应用程序,而此行:
repeated_names = Application.objects.values('school_name', 'category', ).annotate(Count('id')).order_by().filter(id__count__gt=1)
返回重复学校名称的列表。
我期望的是这样的:
(school_name=school_name_1, count=2), (school_name=school_name_2, count=3).. 等等
最佳答案
试试这个:
在您的Views.py
中使用此查询集:
repeated_names = Application.objects.values('school_name', 'category').annotate(Count('id')).order_by().filter(id__count__gt=0) # <--- gt 0 will get all the objects having occurred in DB i.e is greater than 0
gt 0
will get all the objects having occurred in DB i.e is greater than 0
在您的模板
中:
{% for c in repeated_names %}
<ul>
<li>{{c.school_name}}</li>
<li>{{c.id__count}}</li>
<li>{{c.category}}</li>
</ul>
{% endfor %}
关于Django 计算具有重复值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54760985/