本文介绍了什么是更有效的 .objects.filter().exists() 或 get() 包裹在 try的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 django 应用程序编写测试,我想检查一个对象是否已保存到数据库中.哪种方法最有效/最正确?

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?

User.objects.filter(username=testusername).exists()

try:
    User.objects.get(username=testusername)
except User.DoesNotExist:

推荐答案

速度测试:exists() vs. get() + try/except

test.py 中的测试函数:

Speed test: exists() vs. get() + try/except

Test functions in test.py:

from testapp.models import User

def exists(x):
    return User.objects.filter(pk=x).exists()

def get(x):
    try:
        User.objects.get(pk=x)
        return True
    except User.DoesNotExist:
        return False

在 shell 中使用 timeit:

Using timeit in shell:

In [1]: from testapp import test
In [2]: %timeit for x in range(100): test.exists(x)
10 loops, best of 3: 88.4 ms per loop
In [3]: %timeit for x in range(100): test.get(x)
10 loops, best of 3: 105 ms per loop
In [4]: timeit for x in range(1000): test.exists(x)
1 loops, best of 3: 880 ms per loop
In [5]: timeit for x in range(1000): test.get(x)
1 loops, best of 3: 1.02 s per loop

结论:exists()在检查对象是否已保存在数据库中时快 10% 以上.

Conclusion: exists() is over 10% faster for checking if an object has been saved in the database.

这篇关于什么是更有效的 .objects.filter().exists() 或 get() 包裹在 try的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:26