Order Django Query Results by Foreign Key

2020-08-09 06:25发布

问题:

I have a model that is set up as follows:

class Log(models.Model):
    name = models.ForeignKey(User)
    date = models.DateField()
    time = models.TimeField()

I know this does not work, but is there any other way I can run a query something like this:

Logs.objects.filter(date=someDate).order_by('name__last_name')

I just need the final result to be a QuerySet ordered by the last name of the User that is related by the ForeignKey.

I'm really at my wits end about this one. Anything would help: some method that I haven't look at, an actual raw SQL query or even just a general idea to pursue would be greatly appreciated!

回答1:

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