【问题标题】:Django - ordering a filter by the sum of ForeignKey values?Django - 按 ForeignKey 值的总和排序过滤器?
【发布时间】:2011-01-31 19:40:32
【问题描述】:

我有以下型号:

class User:
    name = models.CharField( max_length = 200 )
    problem_user = models.BooleanField(default=False)
    def points_total(self):
        points_added = PointsAdded.objects.filter(user=self)
        points_total = 0
        for point in points_added:
            points_total += point.points
        return points_total

class PointsAdded:
    points = models.IntegerField()
    user = models.ForeignKey( User )

我想返回问题用户为 False 的用户列表,按 points_total 字段排序。

我知道我需要使用注释(如described here),但我是一个新手,并不知道如何使用它,因为示例与我的情况略有不同。这不起作用:

leaders = VideoUser.objects.filter(problem_user=False).pointsadded_set. \
                .annotate(points_total=Sum('points__value')) \
                .order_by('points_total')

替代方法似乎是在上面表达式的 annotate() 部分中写出我的整个 points_total 函数 - 这可能吗?

有没有办法实现我想要使用 Django 功能做的事情,或者我必须回退到 SQL 吗?或者我应该重新设计我的数据库:)

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    您不需要pointsadded_set。如果我正确理解您的模型,这应该可以工作:

    VideoUser.objects.filter(problem_user=False) \
                .annotate(points_total=Sum('pointsadded__points__value')) \
                .order_by('points_total')
    

    【讨论】:

    • 不幸的是,这会在第二行产生 SyntaxError。我也尝试过使用 Sum('points'),但这也给出了 SyntaxError。如果您想要完整的回溯,请告诉我。
    • 抱歉,多留了一个点。现在就试试吧。
    • 仍然没有运气,抱歉 :( 这给了我 'FieldError at /leaderboard/ Cannot resolve keyword 'points' into field。选择是:' 然后是用户字段中的字段列表。看起来好像它不知道应该使用 PointsAdded 字段...?
    • points_total 是一种模型方法,因此无法从查询集中访问。
    • 抱歉,pointsadded 位放错了位置。立即尝试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2021-09-13
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多