Question

my problem is in django orderby clause.i have used two queryset one is state_filter and another is party_filter. without order by clause append the value correctly .using order_by clause then count value is not correctly

My view is:

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'])

without order_by clause answer is:

 [
    {'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}
]

with order_by clause answer is:

[
   {'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}
]

plese give me proper solution

Was it helpful?

Solution

When you execute this :

party_filter=state_filter.values('party_name').annotate(Count('party_name'))

It will perform aggregation . so you get total count according to party_name

Now when you execute this :

party_filter=state_filter.values('party_name').annotate(Count('party_name')).order_by('party_name')

It will perform group by .

Note : aggregate is for the complete resultset, annotate for individual (grouped) rows.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top