Django查询上的values()方法后的Count和Max [英] Count and Max after values() method on Django query

查看:370
本文介绍了Django查询上的values()方法后的Count和Max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Django模型:

I have this Django model:

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行返回字典列表):

but last line gives me (because line 3 returns a list of dictionaries):

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

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

I know that probably something similar has already been answered but Django values() and aggregate() are a bit tricky to me. Which is the right way to do this?

推荐答案

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

You can get the highest count using Django's .latest() method. Though documented for dates, it also works on strings and integers.

这应该为您提供最高玩家数的动作:

This should get you the Action with the highest to_player count:

# 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

这篇关于Django查询上的values()方法后的Count和Max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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