Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very confused... problem using 'annotate' in Django

So I have two models, a Ranking model and a UserRanking model. The app centers on people taking a list of items and ranking them (ex: "Best Movies of 2008"). The Ranking model is the overall aggregate ranked list, which is calculated from all the different UserRankings that people create for that list. So for each Ranking, there are a bunch of different UserRankings, exactly one for each user that gave his/her opinion by submitting their ranked version of the list. The UserRanking model has a ForeignKey field named 'ranking' which points towards the Ranking model.

Anyways, I am trying to gather the popular Rankings. My first step is to get the Rankings with most UserRankings associated to them using this line of code:

popular = Ranking.objects.all().annotate(num_user_rankings=Count('userranking')).order_by('num_user_rankings')[:50]

However, Django gives me a NameError and says: "global name 'Count' is not defined". It doesn't complain about annotate (which is only available in the Django Development version), so that means the Django Development is working right? 'Count' is clearly described in the Django docs as one of several Aggregate functions that can used as arg for annotate. This makes absolutely no sense.

In fact, I just tested it, and I was able to get my page to display using annotate with no paramaters, and it didn't give me any errors (obviously I removed the order_by as well). So annotate does work for sure!

like image 588
Daniel Waltrip Avatar asked Aug 02 '09 00:08

Daniel Waltrip


People also ask

What is difference between annotate and aggregate Django?

Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset.

How do you annotate in Django?

Appending the annotate() clause onto a QuerySet lets you add an attribute to each item in the QuerySet, like if you wanted to count the amount of articles in each category. However, sometimes you only want to count objects that match a certain condition, for example only counting articles that are published.


1 Answers

Did you import Count from django.db.models?

from django.db.models import Count
like image 164
Meredith L. Patterson Avatar answered Oct 06 '22 01:10

Meredith L. Patterson