我有这个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)
我想做以下事情:
这样做我试过了:
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 values()和aggregate()对我来说有点棘手。这是正确的方法吗?
答案 0 :(得分:1)
您可以使用Django的.latest()方法获得最高计数。虽然记录了日期,但它也适用于字符串和整数。
这可以让你获得具有最高to_player数量的Action:
# 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
答案 1 :(得分:0)
错误给出了线索,你应该使用聚合而不是注释max:
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.aggregate(max=Max('count')).filter(count=F('max')) #try to select the max
我不确定最后一个过滤器是否有用但值得尝试。