Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Django Query Results by Foreign Key

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!

like image 602
chandsie Avatar asked Apr 21 '11 22:04

chandsie


1 Answers

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
like image 177
dting Avatar answered Oct 19 '22 17:10

dting