How to get only latest record on filter of foreign key django

南笙酒味 提交于 2020-05-12 04:49:09

问题


I have a table like this Event table

| id | status | date |order(FK)|

| 1 | Planned | 05-02-2015 | 1 |

| 2 | Delivered | 04-02-2015 | 2 |

| 3 | Packed | 03-02-2015 | 3 |

| 4 | Return | 06-02-2015 | 1 |

I want output like this

| id | status | date |order(FK)|

| 2 | Delivered | 04-02-2015 | 2 |

| 3 | Packed | 03-02-2015 | 3 |

| 4 | Return | 06-02-2015 | 1 |

I tried with query = Event.objects.annotate(order_num=Max('date')) but didn't got the expected result. How can i achieve this output


回答1:


Try using the following:

from django.db.models import Max

Event.objects.annotate(max_date=Max('order__event__date')) \
             .filter(date=F('max_date'))


来源:https://stackoverflow.com/questions/46353695/how-to-get-only-latest-record-on-filter-of-foreign-key-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!