Order Django Query Results by Foreign Key

送分小仙女□ 提交于 2020-05-26 10:17:06

问题


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


来源:https://stackoverflow.com/questions/5750409/order-django-query-results-by-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!