所以我有一个注释模型并通过查询
comments = Comments.objects.values('students_id', 'created_at')
我得到这个输出
<QuerySet [
{'students_id': 4, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 2, 'created_at': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at': datetime.date(2019, 6, 24)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 4)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 5, 'created_at': datetime.date(2019, 6, 5)}, {'students_id': 4, 'created_at': datetime.date(2019, 7, 28)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 11)}]>
id = 6的学生有3条评论,id = 4的学生有2条评论。 我需要得到的只是每个学生的一个最新评论。在此示例中,它将如下所示:
<QuerySet [
{'students_id': 2, 'created_at': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at': datetime.date(2019, 6, 24)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 5, 'created_at': datetime.date(2019, 6, 5)}, {'students_id': 4, 'created_at': datetime.date(2019, 7, 28)},]>
提前感谢您的回答!
答案 0 :(得分:0)
您可以使用注释和最大值来获得所需的结果,例如Comments.objects.values('students_id').annotate(Max('created_at'))
输出将类似于<QuerySet [
{'students_id': 2, 'created_at__max': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at__max': datetime.date(2019, 6, 24)},]>
,其中包含students_id和最新created_at。要使用此功能,您必须从django.db.models这样的from django.db.models import Max
答案 1 :(得分:0)
使用此代码:
queryset=Comments.objects.values('students_id', 'created_at').group_by('students_id').annotate(Latest_created_at=Max('created_at'))
queryset.delete()
答案 2 :(得分:0)
在原始SQL中,它将为... WHERE NOT EXISTS(SELECT * FROM Comments cc WHERE cc.student_id = c.student_id AND cc.created_at > c.created_at)
later_comments = Comments.objects.filter(student_id=OuterRef('student_id'),
created_at__gt=OuterRef('created_at'), ).values('created_at', )
latest_comments = Comments.objects.\
annotate(has_later_comments=Exists(later_comments), ).\
filter(has_later_comments=False, )
如果您的created_at
是Date
列(没有时间),则您需要使用=>
而不是>
,因为在此期间可能会创建多个注释一天。因此,查询将包含带有附加列的附加谓词,用于对注释进行排序(例如ID):WHERE cc.created_at > c.created_at OR cc.created_at = c.created_at AND cc.id > c.id
https://docs.djangoproject.com/en/2.2/ref/models/expressions/#exists-subqueries