Account filtering with Django ORM

I have a query that basically "counts all elements of type X and returns elements that exist more than once, together with their values." Right now I have this:

Item.objects.annotate(type_count=models.Count("type")).filter(type_count__gt=1).order_by("-type_count") 

but it returns nothing (the number is 1 for all elements). What am I doing wrong?

Ideally, he should get the following:

 Type ---- 1 1 2 3 3 3 

and return:

 Type, Count ----------- 1 2 3 3 
+6
django orm aggregate
source share
2 answers

To count the number of occurrences of each type, you need to group the type field. In Django, this is done using values to get only this field. So this should work:

 Item.objects.values('group').annotate( type_count=models.Count("type") ).filter(type_count__gt=1).order_by("-type_count") 
+15
source share

This is a logical mistake;)

type_count__gt=1 means type_count > 1 , so if count == 1 it will not be displayed :) use type_count__gte=1 instead - this means type_count >= 1 :)

+2
source share

All Articles