我的问题在于django orderby子句。我使用了两个queryset,一个是state_filter,另一个是party_filter。没有order by子句正确地附加值。使用order_by子句然后计数值不正确
我的观点是:
def const(request):
states = Loksabha.objects.values('state_name').distinct('state_name')
constituency=Loksabha.objects.values('constituency_name').distinct('constituency_name').filter(state_name='MAHARASHTRA')
dataset = Loksabha.objects.all()
state_filter=Loksabha.objects.filter(state_name='MAHARASHTRA',constituency_name='Kolhapur').order_by('id')
party_filter=state_filter.values('party_name').annotate(Count('party_name'))
crime_filter=childcrime_type.objects.filter(state_name='MAHARASHTRA')
womencrime_fltr=womencrime_type.objects.filter(state='MAHARASHTRA')
xdata=[]
ydata=[]
for b in party_filter:
xdata.append(b['party_name'])
ydata.append(b['party_name__count'])
没有order_by子句的答案是:
[
{'party': 'Shiv Sena', 'party__count': 2},
{'party': 'Indian Nationlist Congress', 'party__count': 3},
{'party': 'Nationlist Congress Party', 'party__count': 1},
{'party': 'Republican Party of India(A)', 'party__count': 2},
{'party': 'Bharatiya Janata Party', 'party__count': 1},
{'party': 'Independent', 'party__count': 2}
]
带有order_by子句的答案是:
[
{'party': 'Shiv Sena', 'party__count': 1},
{'party': 'Shiv Sena', 'party__count': 1},
{'party': 'Indian Nationlist Congress', 'party__count': 1},
{'party': 'Indian Nationlist Congress', 'party__count': 1},
{'party': 'Indian Nationlist Congress', 'party__count': 1},
{'party': 'Nationlist Congress Party', 'party__count': 1},
{'party': 'Republican Party of India(A)', 'party__count': 1},
{'party': 'Republican Party of India(A)', 'party__count': 1},
{'party': 'Bharatiya Janata Party', 'party__count': 1},
{'party': 'Independent', 'party__count': 1},
{'party': 'Independent', 'party__count': 1}
]
请给我适当的解决方案
答案 0 :(得分:1)
执行此操作时:
party_filter=state_filter.values('party_name').annotate(Count('party_name'))
它会执行aggregation
。因此,您可以根据party_name
现在执行此操作时:
party_filter=state_filter.values('party_name').annotate(Count('party_name')).order_by('party_name')
它将执行group by
。
注意:聚合用于完整的结果集,为单个(分组)行注释。