Django orm为每个组获取最新信息

2024-06-06 17:45:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Mysql中使用Django 1.6。

我有这些模型:

class Student(models.Model):
     username = models.CharField(max_length=200, unique = True)

class Score(models.Model)
     student = models.ForeignKey(Student)
     date = models.DateTimeField()
     score = models.IntegerField()

我想得到每个学生的最新成绩记录。
我试过:

Score.objects.values('student').annotate(latest_date=Max('date'))

以及:

Score.objects.values('student__username').annotate(latest_date=Max('date'))

如所述Django ORM - Get the latest record for the group 但没用。


Tags: thedjangodatemodelobjectsmodelsusernamelatest
3条回答

如果您的数据库是postgres,它支持^{}on字段,您可以尝试

Score.objects.order_by('student__username', '-date').distinct('student__username')

我相信这会给你学生和数据

Score.objects.values('student').annotate(latest_date=Max('date'))

如果您想要完整的Score记录,似乎必须使用原始SQL查询:Filtering Django Query by the Record with the Maximum Column Value

这应该适用于Django 1.2+和MySQL:

Score.objects.annotate(
  max_date=Max('student__score__date')
).filter(
  date=F('max_date')
)

相关问题 更多 >