[Answered ]-Count multiple terms

2👍

https://docs.djangoproject.com/en/dev/topics/db/aggregation/
says about the order being important. Also, if you have an order_by on the model, that will affect it.
How about …

ee = Term.objects.values("term").annotate(Count("term")).order_by()

0👍

In SQL you cannot do that in only one query, you need a sub query. I guess it is the same with Django, so try this:

ee = Term.objects.extra(select={'count': "SELECT COUNT(term) FROM appname_term AS subtable WHERE subtable.term = appname_term.term"})

It should add a count attribute to every term from ee with the number of rows with this. It applies a subquery on the same relation in the main query. It’s equivalent of SQL:

SELECT *, (
    SELECT COUNT(term) 
    FROM appname_term AS subtable
    WHERE subtable.term = appname_term.term
) AS count
FROM appname_term

Leave a comment