Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A QuerySet by aggregate field value

Let's say I have the following model:

class Contest:     title = models.CharField( max_length = 200 )     description = models.TextField()  class Image:     title = models.CharField( max_length = 200 )     description = models.TextField()     contest = models.ForeignKey( Contest )     user = models.ForeignKey( User )      def score( self ):         return self.vote_set.all().aggregate( models.Sum( 'value' ) )[ 'value__sum' ]  class Vote:     value = models.SmallIntegerField()     user = models.ForeignKey( User )     image = models.ForeignKey( Image ) 

The users of a site can contribute their images to several contests. Then other users can vote them up or down.

Everything works fine, but now I want to display a page on which users can see all contributions to a certain contest. The images shall be ordered by their score. Therefore I have tried the following:

Contest.objects.get( pk = id ).image_set.order_by( 'score' ) 

As I feared it doesn't work since 'score' is no database field that could be used in queries.

like image 880
okoman Avatar asked Jan 24 '09 13:01

okoman


People also ask

What is mean by Queryset?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is difference between aggregate and annotate?

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

What does aggregate do in Django?

When specifying the field to be aggregated in an aggregate function, Django will allow you to use the same double underscore notation that is used when referring to related fields in filters. Django will then handle any table joins that are required to retrieve and aggregate the related value.

What is .annotate in Django?

In the Django framework, both annotate and aggregate are responsible for identifying a given value set summary. Among these, annotate identifies the summary from each of the items in the queryset. Whereas in the case of aggregate, the summary is calculated for the entire queryset.


1 Answers

Oh, of course I forget about new aggregation support in Django and its annotate functionality.

So query may look like this:

Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' ) 
like image 86
Alex Koshelev Avatar answered Oct 06 '22 23:10

Alex Koshelev