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

标签 python django django-models django-queryset

我有这个 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/

相关文章:

python - 在 python 中将可能包含 None 的数组更改为包含 ""的数组

python - SmoothBivariateSpline 给出了意想不到的答案

html - 在 Django 的 TextField 中禁用 HTML 转义

python - 如何将模板包含到 django 包中?

Django:使用自定义主键,我应该指定 unique=True 吗?

python - Flask sqlalchemy 接口(interface)错误

python - Django 表单验证 : get errors in JSON format

python - 在 Python virtualenv 中查找每个编译模块的大小?

python - 如何在Django中用 "SlugField()"增加 "unique=True"的大小?

python - 'NoneType' 对象没有属性 'add'