什么是更有效的.objects.filter()。exists()或get()和一个尝试 [英] What is more efficient .objects.filter().exists() or get() and a try

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

问题描述

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

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

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


解决方案

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



test.py 中的测试功能:



来自testapp.models import的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

返回User.objects.filter(pk = )

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

在shell中使用 timeit

 在[1]中:从testapp导入测试
在[2]中:x在范围(100)中的%timeit:test .exists(x)
10个循环,最好的3:88.4 ms每循环
在[3]中:x在范围(100)中的时间:test.get(x)
10循环,最好3:105 ms每循环
在[4] :x的范围(1000)的时间:test.exists(x)
1循环,最好3:880 ms每循环
在[5]中:x在范围(1000)中的时间:test .get(x)
1循环,最佳3:1.02每循环

结论 exists()超过10%的速度,用于检查对象是否已保存在数据库中。 p>

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()

or

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

解决方案

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

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

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

这篇关于什么是更有效的.objects.filter()。exists()或get()和一个尝试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆