django orm查询性能
我试图为我的Django应用找到最好的Django查询。我使用默认的SQLite DB作为后端。我正在使用 timeit
找到查询时间。
>>> import timeit
>>>
>>> setup_arg = 'from .models import AwsConsoleAccess'
>>> stmt1 = """AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785')"""
>>> stmt2 = """AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785').values('status')"""
>>>
>>>
>>> print(timeit.timeit(setup=setup_arg, stmt=stmt1, number=100) * 1000, 'ms')
7.873513997765258 ms
>>> print(timeit.timeit(setup=setup_arg, stmt=stmt2, number=100) * 1000, 'ms')
11.816384001576807 ms
执行SQL查询:
>>> print(AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785').query)
SELECT "aws_console_awsconsoleaccess"."created",.....(all fields) FROM "aws_console_awsconsoleaccess" WHERE "aws_console_awsconsoleaccess"."request_id" = 8548a2d54bb74fa9add2a41219dc8785
>>> print(AwsConsoleAccess.objects.filter(request_id='8548a2d5-4bb7-4fa9-add2-a41219dc8785').values('status').query)
SELECT "aws_console_awsconsoleaccess"."status" FROM "aws_console_awsconsoleaccess" WHERE "aws_console_awsconsoleaccess"."request_id" = 8548a2d54bb74fa9add2a41219dc8785
从理论上从表
选择字段应比 SELECT *从表
中选择 *,但我的结果没有反映它。
- 我是否正确进行了测试?
- 还有其他方法可以测试Django Orm中两个查询之间的性能吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有考虑到,即创建QuerySet时,没有对数据库进行实际查询。仅当实际需要查询结果时,查询才会运行。
因此,当您编写
model.objects.filter(...)
时,所有的工作都是创建查询。取而代之的是,您应该通过将其转换为列表来强制对QuerySet的评估。这实际上将运行查询并为您提供更准确的结果:You have not considered the fact that QuerySets are lazy, that is when you create a queryset no actual query is made to the database. The query will run only when the results of the query are actually needed.
So when you write
Model.objects.filter(...)
all that does is create a query. You should instead force the evaluation of the queryset, for example by converting it to a list. This will actually run the query and give you more accurate results: