本文介绍了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()现在我想获得每个学生的最新成绩记录。 i已尝试
Score.objects.values('student')。annotate(latest_date = Max('date'))我也尝试过
Score.objects.values('student__username')。annotate(latest_date = Max('日期'))如 Django ORM - 获取组的最新记录 ,但没有帮助。
解决方案这应该适用于Django 1.2+和MySQL:
Score.objects.annotate(max_date = Max(' student__score__date'))。filter(date = F('max_date'))
I am using django 1.6 with Mysql
I have this models
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()Now i want to get the latest score record for each student. i have tried
Score.objects.values('student').annotate(latest_date=Max('date'))i have also tried
Score.objects.values('student__username').annotate(latest_date=Max('date'))as described Django ORM - Get latest record for group but it did not help.
解决方案This should work on Django 1.2+ and MySQL:
Score.objects.annotate(max_date=Max('student__score__date')).filter(date=F('max_date'))
更多推荐
Django orm获取每组最新消息
发布评论