我正在将 Django 1.6 与 Mysql 一起使用。
我有这些模型:
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'))
最佳答案
如果您的数据库是支持 distinct()
的 postgres在现场你可以尝试
Score.objects.order_by('student__username', '-date').distinct('student__username')
关于python - Django orm 为每个组获取最新信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923877/