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

标签 python django django-queryset django-orm

我正在将 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'))

如所述Django ORM - Get the latest record for the group 但它没有帮助。

最佳答案

如果您的数据库是支持 distinct() 的 postgres在现场你可以尝试

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

关于python - Django orm 为每个组获取最新信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923877/

相关文章:

python - 在 Django 中提交表单后重定向到带参数的主页

Django QuerySet 包含重复的条目

python - 使用 PIL/python 渲染数学文本

python - django-registration,修复一个故障

python - Django : Parsing Json data to template

python - 查询集花费太多时间

python - 如何在我自己的 View 中使用 Django 管理列表和过滤?

python - 测试 pandas DataFrame 是否存在

具有 unicode 范围的 Python 正则表达式匹配不在范围内的字符

python - Django 自定义权限无法被识别?