[Answer]-Django ORM: using extra to order models by max(datetime field, max(datetime field of related items))

1👍

Your join is wrong. It should be:

maps_map join maps_mapitem on maps_map.id = maps_mapitem.map_id

As it stands you’re forcing the PKs to be equal, not the map’s PK to match the items’ FKs.

edit

I suspect your subquery isn’t joining against the main maps_map part of the query. I am sure there are other ways to do this, but this should work:

Map.objects.extra(select={
  "last_updated": "greatest(modified_date, (select max(maps_mapitem.modified_date) from maps_mapitem where maps_mapitem.map_id = maps_map.id))"})

Leave a comment