如何仅获取外键django过滤器上的最新记录 [英] How to get only latest record on filter of foreign key django
问题描述
我有一个这样的表
事件表
I have a table like this Event table
| 1 |计划中| 2015年5月2日| 1 |
| 1 | Planned | 05-02-2015 | 1 |
| 2 |已交付2015年4月2日| 2 |
| 2 | Delivered | 04-02-2015 | 2 |
| 3 |包装好的2015年3月2日| 3 |
| 3 | Packed | 03-02-2015 | 3 |
| 4 |返回| 2015年6月2日| 1 |
| 4 | Return | 06-02-2015 | 1 |
我想要这样的输出
| 2 |已交付2015年4月2日| 2 |
| 2 | Delivered | 04-02-2015 | 2 |
| 3 |包装好的2015年3月2日| 3 |
| 3 | Packed | 03-02-2015 | 3 |
| 4 |返回| 2015年6月2日| 1 |
| 4 | Return | 06-02-2015 | 1 |
我尝试用
查询= Event.objects.annotate(order_num = Max('date'))
但没有得到预期的结果。
如何实现此输出
I tried with query = Event.objects.annotate(order_num=Max('date')) but didn't got the expected result. How can i achieve this output
推荐答案
尝试使用以下内容:
from django.db.models import Max
Event.objects.annotate(max_date=Max('order__event__date')) \
.filter(date=F('max_date'))
这篇关于如何仅获取外键django过滤器上的最新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!