按聚合字段值排序QuerySet [英] Order a QuerySet by aggregate field value
问题描述
假设我有以下模型:
class Contest:
title = models.CharField(max_length = 200)
description = models.TextField()
class Image:
title = models.CharField(max_length = 200)
description = models.TextField b $ b contest = models.ForeignKey(Contest)
user = models.ForeignKey(User)
def score(self):
return self.vote_set.all (model.Sum('value'))['value__sum']
class Vote:
value = models.SmallIntegerField()
user = models.ForeignKey
image = models.ForeignKey(Image)
网站的用户可以贡献他们的图片到几个比赛。然后其他用户可以投票或投票。
一切正常,但现在我想显示一个页面,用户可以看到所有的贡献的一个特定的比赛。图像应按他们的分数排序。
因此,我尝试以下:
Contest.objects.get(pk = id).image_set.order_by('分数')
因为我担心它不工作,因为'score'
当然,我忘记了Django中的新的聚合支持和它的注释
功能。
所以查询可能如下所示:
Contest.objects.get(pk = id).image_set.annotate(score = Sum('vote__value'))。order_by('score')
pre>
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 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.
解决方案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' )
这篇关于按聚合字段值排序QuerySet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!