Which is more efficient .objects.filter (). Exists () or get () and try

I am writing tests for a django application and I want to check if an object is saved in the database. What is the most efficient / correct way to do this?

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

or

 try: User.objects.get(username=testusername) except User.DoesNotExist: 
+5
source share
3 answers

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

Tested 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 the 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() over 10% faster to check if an object is stored in the database.

+4
source

If you do not need a user, the first one is more efficient since it does not instantiate the object.

+3
source

I would say .exists() is the best way to do this if you are just trying to determine if an object matching the filter exists. The reason is that your example for .get() covers only 2 of 3 scenarios. There is also a MultipleObjectsReturned exception that occurs when more than one object matching a filter is found.

I would use .get() to get one instance and use exceptions to catch exception workflows.

+1
source

Source: https://habr.com/ru/post/1012802/


All Articles