Django计算具有重复值的行

问题描述 投票:1回答:1

我正在研究在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])

查询变量返回一个查询集,其中的应用程序具有字段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)..等

django django-models django-views
1个回答
0
投票

试试这个:

在你的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将获得在DB中发生的所有对象,即大于0

在你的Template

 {% for c in repeated_names %}

 <ul>

 <li>{{c.school_name}}</li>

 <li>{{c.id__count}}</li>

 <li>{{c.category}}</li>


</ul>

{% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.