2

I am working on counting rows with duplicate values in a django Model and running into a little hitch. I have looked at this question Django Select Rows with duplicate Values

and the solution is perfect. But my question is, What if I want to Count the rows and group them according to: Name of the duplicated row, and how many times it has been duplicated, instead of just displaying the name of the repeated rows.

my code so far:

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

The query variable returns a queryset with the Applications that have duplicate values for the field school_name while this line:

repeated_names = Application.objects.values('school_name', 'category', ).annotate(Count('id')).order_by().filter(id__count__gt=1)

returns a list of the duplicated school names.

What I expect is something like:

(school_name=school_name_1, count=2), (school_name=school_name_2, count=3).. etc.

2
  • You obviously are rendering this data in front end right? Commented Feb 19, 2019 at 7:48
  • @ans2human yes, that's right Commented Feb 19, 2019 at 7:50

1 Answer 1

3

Try this:

In your Views.py use this queryset:

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

In your Template:

 {% for c in repeated_names %}

 <ul>

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

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

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


</ul>

{% endfor %}
Sign up to request clarification or add additional context in comments.

11 Comments

This worked with the client_ ommitted. But is there no way I way I can do this in the views?
And also, how can I get access to the values of other fields on the same row?
@Abedy Yes Updated the answer, You're already doing it in the views. To get rest of the fields data i have updated the query. Please check
The updated query seems to have a bug. It only displays one item.
@Abedy update the question with query you are using now and also the error you're getting. I'll check.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.