如何仅获取外键django过滤器上的最新记录 [英] How to get only latest record on filter of foreign key django

查看:90
本文介绍了如何仅获取外键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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆