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:
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Retrieving Single Objects from QuerySets We can do this using the get() method. The get() returns the single object directly. Let's see the following example. As we can see in both examples, we get the single object not a queryset of a single object.
objects. get(pk=1) You can use any query expression with get() , just like with filter() - again, see Field lookups below. Note that there is a difference between using get() , and using filter() with a slice of [0] . If there are no results that match the query, get() will raise a DoesNotExist exception.
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With