[英]Django ordering efficiency with joins - can I force a subquery?
This concerns Django 1.4.6 with a MySQL backend. 这涉及带有MySQL后端的Django 1.4.6。 When doing an ordered query with joins, Django will put the ordering clause at the end of the query.
使用连接进行有序查询时,Django会将ordering子句放在查询的末尾。 Imagine some models like
想象一些像
class MainObject(models.Model):
pass
class RelatedObject(models.Model):
main_object = models.ForeignKey(MainObject)
If you have a lot of these and try a query such as RelatedObject.objects.select_related('main_object').order_by('-id') limit 20000
it is, depending on how many joins there are, almost twice as slow as the same query without an ordering: RelatedObject.objects.select_related('main_object') limit 20000
如果您有很多这样的对象,并尝试执行诸如
RelatedObject.objects.select_related('main_object').order_by('-id') limit 20000
类的查询,则该RelatedObject.objects.select_related('main_object').order_by('-id') limit 20000
,这取决于连接的数量,几乎是连接速度的两倍。没有排序的相同查询: RelatedObject.objects.select_related('main_object') limit 20000
This is because the query generated is 这是因为生成的查询是
SELECT app_relatedobject.id, app_relatedobject.main_object_id, app_mainobject.id
FROM app_relatedobject
INNER JOIN app_mainobject ON (app_relatedobject.main_object_id = app_mainobject.id)
ORDER BY app_relatedobject.id DESC
LIMIT 20000
which is much slower than the equivalent 比同等的慢很多
SELECT tmp.id, tmp.main_object_id, app_mainobject.id
FROM (
SELECT app_relatedobject.id, app_relatedobject.main_object_id
FROM app_relatedobject
ORDER BY app_relatedobject.id DESC
LIMIT 20000) tmp
INNER JOIN app_mainobject ON (app_relatedobject.main_object_id = tmp.id)
Is there any way to do what I'm trying to achieve in an efficient way? 有什么方法可以有效地完成我要达到的目标吗? For context, I'm using the django admin system and have a list_display that requires lots of joins across thousands of large records.
对于上下文,我使用的是django管理系统,并且具有list_display,它需要跨数千个大记录进行大量联接。 I can't use raw sql because the rest of the admin system requires a queryset for pagination and filtering.
我无法使用原始sql,因为管理系统的其余部分需要用于分页和过滤的queryset。
Any help is greatly appreciated. 任何帮助是极大的赞赏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.