[英]How can I order by ForeignKey field itself in django without join?
So I have a model MyModel
with a ForeignKey field fkfield
. 因此,我有一个MyModel
模型,其中的ForeignKey字段为fkfield
。 And i need to do something like this (simplified): 我需要做这样的事情(简化):
MyModel.objects.values_list('id', 'fkfield').order_by('fkfield')
For example I want to groupby
them further by fkfield
so I need my objects to be sorted by this field. 例如,我想groupby
进一步他们fkfield
所以我需要我的对象由该字段排序。 And the only thing I will use later is fkfield_id
. 我以后将使用的唯一东西是fkfield_id
。 I mean I dont need any data from related model. 我的意思是我不需要相关模型的任何数据。
But django performs a join sql query (as described in docs ) and uses related model's ordering
. 但是django执行联接sql查询(如docs中所述 )并使用相关模型的ordering
。 The same happens if i explicitly try to order by id
: 如果我明确尝试按id
排序,也会发生相同的情况:
MyModel.objects.values_list('id', 'fkfield').order_by('fkfield__id')
and I get: 我得到:
SELECT `mymodel`.`id`,
`mymodel`.`fkfield_id`
FROM `mymodel`
LEFT OUTER JOIN `related_table`
ON ( `mymodel`.`fkfield_id` = `related_table`.`id` )
ORDER BY
`related_table`.`id` ASC
What i really expect is: 我真正期望的是:
SELECT `id`,
`fkfield_id`
FROM `mymodel`
ORDER BY
`fkfield_id` ASC
But I can't find a way to do it. 但是我找不到办法。 .order_by('fkfield_id')
raises exception that says that there is no such a field. .order_by('fkfield_id')
引发异常,表明没有这样的字段。
I managed to get things work using extra
but I can't understand why such a simple and obvious behaviour can't be used without hacks. 我设法使事情变得extra
但是我不明白为什么没有黑客就不能使用如此简单和明显的行为。 Or maybe i missed smth? 还是我错过了某物?
UPDATE: models.py 更新:models.py
class Producer(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name',)
class Collection(models.Model):
name = models.CharField(max_length=100)
producer = models.ForeignKey('Producer')
class Meta:
ordering = ('name',)
print Collection.objects.values_list('producer', 'id').order_by('producer').query
>>> SELECT `catalog_collection`.`producer_id`, `catalog_collection`.`id`
>>> FROM `catalog_collection`
>>> INNER JOIN `catalog_producer` ON
>>> (`catalog_collection`.`producer_id` = `catalog_producer`.`id`)
>>> ORDER BY `catalog_producer`.`name` ASC
Try 尝试
.order_by('fkfield')
My query is 我的查询是
Post.objects.values('author', 'id').order_by('author')
as sql: 作为SQL:
SELECT "blogs_post"."author_id",
"blogs_post"."id"
FROM "blogs_post"
ORDER BY "blogs_post"."author_id" ASC
UPDATE UPDATE
Kind of messy solution: 有点凌乱的解决方案:
MyModel.objects.extra(select={'fkfield_id': 'fkfield_id'})\
.values_list('id', 'fkfield_id')\
.order_by('fkfield_id')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.