Speed test: `exists()` vs. `get() + try/except
From Try2Explore.com by Abraham
问题描述
I’m writing tests for a django application and I want to check if an object has been saved to the database. Which is the most efficient/correct way to do it?
1 | User.objects.filter(username=testusername).exists() |
or
1 | try: |
解决方案
Speed test: exists() vs get() + try/except
Test functions in test.py:
1 | from testapp.models import User |
Using timeit in shell:
1 | In [1]: from testapp import test |
Conclusion: exists() is over 10% faster for checking if an object has been saved in the database.
说明
在只要求判断数据库是否存在某条数据的情况,使用 exists()
有更高的效率。
在需要获得实例并作检查等情况下,get() + try/except
有着更广的应用场景。
- 本文标题:Speed test: `exists()` vs. `get() + try/except
- 本文作者:iSTEP
- 创建时间:2021-08-07 21:54:53
- 本文链接:https://istep.github.io/2021/08/07/Speed-test-exists-vs-get-try-except/
- 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
评论