[Answer]-Django: How to construct query that includes related latest?

1👍

Sometimes, you just have to fallback to the good-and-old SQL using extra(). How would you resolve it?

Job.objects.extra(
    select={'lastest_state': '''(select state from app_statushistory T1
    join app_attempt T2 on T1.attempt_id=T1.id
    where T2.job_id=app_job.id
    order by id desc limit 1)'''},
    where=['lastest_state=%s'],
    params=['final'])

Replace any app_<tablename> ocurrences with the actual table names (and order by id with another sort if you have it).

Here are the docs for extra().

Leave a comment