Order Django Query Results by Foreign Key

The query you entered looks valid.

Look at the order by docs here.

Is it not working for you?

for example (formatted for easier reading):

    >>> units = Unit.objects.filter(color="red").order_by('location__label')
    >>> print units.query
    SELECT `samples_unit`.`id`, `samples_unit`.`location_id`, `samples_unit`.`color` 
      FROM `samples_unit` 
INNER JOIN `storages_container` 
        ON (`samples_unit`.`location_id` = `storages_container`.`id`) 
     WHERE `samples_unit`.`color` = red  
  ORDER BY `storages_container`.`label` ASC

Leave a Comment