Django orm获取每组最新消息

编程入门 行业动态 更新时间:2024-10-21 15:51:41
本文介绍了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获取每组最新消息

本文发布于:2023-10-24 14:34:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524191.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最新消息   每组   Django   orm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!