views:

34

answers:

2

Hello, I have a query that's basically "count all the items of type X, and return the items that exist more than once, along with their counts". 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 count is 1 for all items). What am I doing wrong?

Ideally, it should get the following:

Type
----
1
1
2
3
3
3

and return:

Type, Count
-----------
1     2
3     3
+2  A: 

It's logical error ;)

type_count__gt=1 means type_count > 1 so if the count == 1 it won't be displayed :) use type_count__gte=1 instead - it means type_count >= 1 :)

bx2
I only want those that have count *more* than one, so that's correct...
Stavros Korokithakis
yea but you said the count is 1 for each one - that's the reason why nothing is displayed :)
bx2
There are duplicate types, yet the count for everything is 1. This is wrong, but I don't know why the count isn't the correct one.
Stavros Korokithakis
+2  A: 

In order to count the number of occurrences of each type, you have to group by the type field. In Django this is done by using values to get just that field. So, this should work:

Item.objects.values('group').annotate(
     type_count=models.Count("type")
).filter(type_count__gt=1).order_by("-type_count")
Daniel Roseman
yea - that's right, but use `type` instead of `group` :) it will return something like: [{'type': u'X', 'type_count': 2}] - why didn't I said that earlier :)
bx2
I think you meant "type" there instead of "group", it *did* work when I did this without the __gt part, but with the __gt part it just throws "dict object has no attribute type_count", which tells me that it's trying to access it as an column...
Stavros Korokithakis
That's strange - I've checked it and it works like a charm. Btw. when it's saying about no type_count attr in dict it means the dict generated by aggregate - it does not try to acces it like a column. The results should be like I wrote above. Check it in django shell to be sure.
bx2
Yep, you're right. I forgot it was turned into a dictionary and was trying an attribute lookup. It works very well now, thank you! I'll leave this answer as correct because I can't split it in two :(
Stavros Korokithakis