我有以下结构:
class Player(models.Model):
name = models.CharField(max_length=50)
dob = models.DateField(max_length=80)
class Game(models.Model):
name = models.CharField(max_length=50)
class Attempts(models.Model):
player = models.ForeignKey("Player")
game = models.ForeignKey("Game")
won = models.BooleanField()
Attempts 类记录每个玩家的尝试以及他是赢还是输游戏。现在我想获取在 agr 组中尝试特定游戏的人数。例如,0-18 岁的人尝试了 5 次游戏等on.我在django用户中查阅了以下这篇文章并制作了以下代码:
ranges = [(0,18),(18,25),(25,50)]
now = datetime.now()
groups = {}
for (a,b) in ranges:
# print str(a) + " " +str(b)
newer_date = (now - relativedelta(years=a)).date()
older_date = (now - relativedelta(years=b)).date()
print str(newer_date)
print str(older_date)
groups[str(a)+","+str(b)] = Attempts.objects.filter(game__pk = "101",player__dob__range=(older_date,newer_date)).count()
这也给出了正确的结果:
{"0,18": 2, "25,50": 1, "18,25": 1}
此代码所做的查询如何等于范围内的类别数。我想知道如何在一个 ORM 查询中获取这些数据。是否可以这样做?