【问题标题】:How can I sort a django queryset by the total of two fields?如何按两个字段的总数对 django 查询集进行排序?
【发布时间】:2012-05-23 10:33:37
【问题描述】:

我想注释一个对象列表(每个对象都有一组tags 和一个整数值points),以便它们可以按标签总数加上点数进行排序。

但是,我找不到任何方法来用两列的总和来注释对象。关于我应该如何做到这一点的任何想法?

这些是我正在使用的模型,leaderboard() 函数是我在工作中遇到困难的模型。

class Game (models.Model):
    users = models.ManyToManyField(User, through='Player', related_name='games')

    def leaderboard (self):
        """ Return a list of players ranked by score, where score is the total of the count of the players tags and their points. """
        leaderboard = self.player_set.annotate(
            tagcount=models.Count('tags')
        ).extra(
            select={'score': 'tagcount + points'},
            order_by=('score',)
        )
        return leaderboard

class Player (models.Model):
    game = models.ForeignKey(Game)
    user = models.ForeignKey(User)
    points = models.SmallIntegerField(default=0, help_text="Points that have been awarded to the player")

class Tag (models.Model):
    game = models.ForeignKey(Game, related_name='tags')
    player = ForeignKey(Player, related_name='tags')

编辑 2: 使用额外的解决方案

好的,所以我有额外的工作,通过手动计算标签的数量并将其添加到点。

def leaderboard (self):
    """ Return a list of players ranked by score, where score is the total of the count of the players tags and their points. """
    return self.players.extra(
        select={'score': '(select count(*) from kaos_tag where kaos_tag.tagger_id=kaos_player.id) + points'},
        order_by=('-score',)
    )

【问题讨论】:

  • Django order_by sum of fields 的可能重复项
  • @DrTyrsa 我正在尝试做同样的事情,但其中一个字段是计数而不是实际字段。
  • 我会选择denolmazition:将tags_count 归档到模型中并用信号更新它。或者使用raw queries 作为替代。

标签: django django-models django-orm


【解决方案1】:

使用额外的

players.objects.extra(
    select={'fieldsum':'tags__count + points'},
    order_by=('fieldsum',)
)

【讨论】:

  • @Efazati 这不起作用 - 数据库不做与 django 相同的翻译,因此抛出:Caught DatabaseError while rendering: no such column: tags__count
  • @Ziaix 将您的模型添加到您的任务中
  • @Efazati 我已经更新了它,其中包含正在使用的模型的摘要。
猜你喜欢
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 2014-04-12
  • 2020-08-16
  • 2019-01-13
  • 2021-11-26
相关资源
最近更新 更多