sort django queryset by latest instance of a subset of related model
Posted
by
rsp
on Stack Overflow
See other posts from Stack Overflow
or by rsp
Published on 2012-12-07T05:01:29Z
Indexed on
2012/12/07
5:03 UTC
Read the original article
Hit count: 1232
I have an Order model and order_event model. Each order_event has a foreignkey to order. so from an order instance i can get: myorder.order_event_set
. I want to get a list of all orders but i want them to be sorted by the date of the last event. A statement like this works to sort by the latest event date:
queryset = Order.objects.all().annotate(latest_event_date=Max('order_event__event_datetime')).order_by('latest_event_date')
However, what I really need is a list of all orders sorted by latest date of A SUBSET OF EVENTS. For example my events are categorized into "scheduling", "processing", etc. So I should be able to get a list of all orders sorted by the latest scheduling event. This django doc (https://docs.djangoproject.com/en/dev/topics/db/aggregation/#filter-and-exclude) shows how I can get the latest schedule event using a filter but this excludes orders without a scheduling event.
I thought I could combine the filtered queryset with a queryset that includes back those orders that are missing a scheduling event...but I'm not quite sure how to do this. I saw answers related to using python list but it would be much more useful to have a proper django queryset (ie for a view with pagination, etc.)
© Stack Overflow or respective owner