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

问题描述

我正在为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() get()+试试/ except


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

在外壳中使用 timeit

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:26