按外键排序Django查询结果 [英] 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')
我只需要最终结果是 QuerySet
,该查询集由与 ForeignKey
。
I just need the final result to be a QuerySet
ordered by the last name of the User that is related by the ForeignKey
.
我真的很想知道这件事。
任何东西都可以帮助您:非常感谢一些我没看过的方法,实际的原始SQL查询甚至只是一般的想法!
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!
推荐答案
您输入的查询看起来是有效的。
The query you entered looks valid.
请查看文档> 此处
。
它不适合您吗?
例如(格式为易于阅读):
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
这篇关于按外键排序Django查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!