[Answered ]-Complex compound order_by django query

2👍

I think you want:

Title.objects.select_related().extra(
    select={'sort_title':"COALESCE(`tv_show`.`title`, `title`.`title`)"},
    order_by=['sort_title']
)

So you are adding a “virtual” field to the SELECT clause, COALESCE will give you the first non-null value, so sort_title will be the TV show’s title if there is one, or the regular title. Then you can sort by the name you give it. The select_related() is so that the join is done in 1 query, I am not sure what the table names are but you can take it from there…

Leave a comment