按聚合字段值的 QuerySet [英] A QuerySet by aggregate field value

查看:35
本文介绍了按聚合字段值的 QuerySet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下模型:

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' )

我担心它不起作用,因为 '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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆