python - Complex compound order_by django query -
i have following 2 models title of movies , tv:
title - id - title - show_name (fk, nullable) tvshow - id - title
here example data entries:
episode_title - (1, "terminator", null) - (2, "zzz", 1) --> fk tvshow (1, "seinfeld") - (3, "abyss", null)
here how should sorted:
- abyss (sort episode title if show null) - seinfeld - zzz (sort show title if show not null) - terminator (sort title if show null)
how django queryset? have now, incorrect --
title.objects.filter('title', 'show__title')
i think want:
title.objects.select_related().extra( select={'sort_title':"coalesce(`tv_show`.`title`, `title`.`title`)"}, order_by=['sort_title'] )
so adding "virtual" field select
clause, coalesce
give first non-null value, sort_title tv show's title if there one, or regular title. can sort name give it. select_related()
join done in 1 query, not sure table names can take there...
Comments
Post a Comment