Django视图响应时间问题
您好,我有很多从查询中获得的对象,查询集尚未评估,当我将对象列表传递给分页器对象时,花了 14 秒才返回分页器对象,这是因为它正在评估列表中的所有对象,这需要时间(可能会击中数据库)。
在将查询集发送到分页器对象之前,我强制评估查询集为:
ds_objects = list(ds_objects)
猜猜现在分页在返回对象时花费了 0.0 秒,但问题仍然存在,所有时间都由 ds_objects = list(ds_objects) 占用,我怎样才能有效地做到这一点,以便我的视图响应时间缩短至仅 2 或 3 秒?我还没有找到任何最佳解决方案:s
Hi i have lots of objects which i get from query, the queryset is not yet evaluated, when i pass objectlist to paginator object it took 14 seconds to return paginator object, it is because it is evaluating the all objects in list which took time (hitting db may be).
I forcefully evaluated queryset before sending it to paginator object as:
ds_objects = list(ds_objects)
Guess what now pagination took 0.0 seconds in returning object, but the problem still remain now all time is taken by ds_objects = list(ds_objects), how can i do it efficiently so that my view response time reduced to just 2 or 3 seconds? i have not found any best solution :s
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是 JOIN(因此
select_lated
)对于查询速度并不重要。无论如何,当您执行values()
查询时,您实际上并不需要select_lated
因为您获得的唯一字段是指定为values()< 的字段/code> 参数,并且它们无论如何都是由 JOIN 检索的。
要了解为什么需要这么长时间,您可以执行以下操作:
使用修改它打印出“原始sql”
(它实际上不是SQL,但它应该足够接近)以在SQL客户端中运行,就像django自己的
manage.py dbshell
。执行它,记下时间。然后执行
EXPLAIN ...
(将查询放在点中),您可能会看到一些“全表扫描”消息向数据库表中受影响的列添加适当的索引,然后执行再次查询。索引可能是这样的:
当你对索引满意时,将其创建命令存储在
文件 app/sql/modelname.sql,这将在任何新部署中创建索引。
My guess is that the JOINs (so the
select_related
) are not important for the query speed. Anyway when you do avalues()
query you don't really needselect_related
because the only fields you'll ever get are those specified asvalues()
arguments, and they are retrieved by JOINs anyway.To see why it takes so long, you can do the following:
Print out the "raw sql" with
Modify it (it's not actually SQL, but it should be near enough) to be run in a SQL client, like django's own
manage.py dbshell
.Execute it, take note of the time. Execute then
EXPLAIN ...
(put your query in the dots), you will probably see some "full table scan" messageAdd a proper index to the database table, over the affected columns, and execute the query again. The index will probably be this:
When you are satisfied with the index, store its creation commmand in the
file
app/sql/modelname.sql
, this will create the index in any new deployment.