QuerySet by聚合字段值 [英] 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()
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.
推荐答案
哦,我当然忘记了关于Django中新的聚合支持及其 annotate
功能。
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 by聚合字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!