Django:日期范围查询性能问题
在 MySQL 后端,Django 将 filter(date__year=2011)
转换为 ... WHERE date BETWEEN 2011-01-01 00:00:00 和 2011-12-31 23:59:59.99
在 SQL 中,执行需要 3 秒。如果我手动删除时间部分并将其运行为 ... WHERE date BETWEEN 2011-01-01 和 2011-12-31
,则执行时间会下降 1/100 至 30 毫秒。
似乎如何解释日期范围查询存在一个根本问题。有什么想法可以解决这个问题吗?
如果我找不到使用 Django ORM 的方法,我将向模型添加一个额外的年份字段来存储年份并对该整数年份字段进行查询。
谢谢您的宝贵时间。
ps:由于我无法控制的限制,环境是Django 1.1。这可能会在较新版本的 Django 中得到修复或更好地优化。
On MySQL backend, Django converts filter(date__year=2011)
to ... WHERE date BETWEEN 2011-01-01 00:00:00 and 2011-12-31 23:59:59.99
in SQL, which takes 3 seconds to execute. If I manually remove the time part and run it as ... WHERE date BETWEEN 2011-01-01 and 2011-12-31
, the execution time drops by 1/100 to 30 msec.
It seems that there is a fundamental problem with how the date range queries are interpreted. Any ideas to get around this?
If I cannot find a way using the Django ORM, I will add an extra year field to the model to store the year and do the query on that integer year field.
Thank you for your time.
p.s: For restrictions beyond my control, the environment is Django 1.1. This may be fixed or better optimized in newer versions of Django.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你试过
范围
< /强> ?看起来 django 生成的 sql 等于你的原始 sql。适用于 1.1.filter(date__range(datetime.date(2011,1,1), datetime.date(2011,12,31))
相当于:
SELECT ... WHERE date BETWEEN “2011-01-01”和“2011-12-31”;
have you tried
range
? looks like the django's generated sql is equal to your raw sql. Works with 1.1.filter(date__range(datetime.date(2011,1,1), datetime.date(2011,12,31))
equivalent to:
SELECT ... WHERE date BETWEEN '2011-01-01' and '2011-12-31';