yos*_*ssi 44 python django django-orm django-queryset
我正在使用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()
Run Code Online (Sandbox Code Playgroud)
现在我想获得每个学生的最新成绩记录.
我试过了
Score.objects.values('student').annotate(latest_date=Max('date'))
Run Code Online (Sandbox Code Playgroud)
我也试过了
Score.objects.values('student__username').annotate(latest_date=Max('date'))
Run Code Online (Sandbox Code Playgroud)
如描述Django ORM - 获取组的最新记录, 但它没有帮助.
Roh*_*han 43
如果您的数据库是postgres,支持distinct()on field,您可以尝试
Score.objects.order_by('student__username', '-date').distinct('student__username')
Run Code Online (Sandbox Code Playgroud)
nit*_*wit 33
这应该适用于Django 1.2+和MySQL:
Score.objects.annotate(
max_date=Max('student__score__date')
).filter(
date=F('max_date')
)
Run Code Online (Sandbox Code Playgroud)
我相信这会给你学生和数据
Score.objects.values('student').annotate(latest_date=Max('date'))
Run Code Online (Sandbox Code Playgroud)
如果您想要完整的Score记录,似乎您将不得不使用原始 SQL 查询:Filtering Django Query by the Record with the Maximum Column Value