gpt4 book ai didi

python - Django 查询上的 value() 方法后的计数和最大值

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:35 25 4
gpt4 key购买 nike

我有这个 Django 模型:

class Action(models.Model):
id = models.AutoField(primary_key=True)
game = models.ForeignKey(Game)
step = models.ForeignKey(Step)
from_player = models.ForeignKey(Player)
to_player = models.ForeignKey(Player)
type = models.ForeignKey(ActionType)
timestamp = models.DateTimeField(default=timezone.now)

我想要执行以下操作:

  1. 按游戏、步骤和类型进行过滤
  2. 查找获得最多操作次数的玩家

为此我尝试过:

v = Action.objects.filter(game=1, step=2)
v = v.filter(type=3)
v = v.values('to_player').order_by().annotate(count=Count('to_player'))
v = v.annotate(max=Max('count')).filter(count=F('max')) #try to select the max

但最后一行给了我(因为第 3 行返回字典列表):

Cannot compute Max('count'): 'count' is an aggregate

我知道可能已经回答了类似的问题,但 Django value() 和aggregate() 对我来说有点棘手。哪种方法是正确的?

最佳答案

您可以使用 Django 的 .latest() 获得最高计数方法。虽然记录了日期,但它也适用于字符串和整数。

这应该会为您提供 to_player 计数最高的操作:

# combined the filters, no need to separate into two steps
v = Action.objects.filter(game=1, step=2, type=3)
v = v.annotate(count=Count('to_player'))
v = v.latest('count') # will return Action with the highest count

关于python - Django 查询上的 value() 方法后的计数和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23279393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com