Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more efficient .objects.filter().exists() or get() wrapped on a try

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:
like image 469
Abraham Avatar asked May 09 '14 10:05

Abraham


People also ask

What is objects filter in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Which can be used to retrieve an object directly instead of a QuerySet?

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.

What is objects get in Django?

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.

What is QuerySet in Django?

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.


1 Answers

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.

like image 127
pcoronel Avatar answered Sep 28 '22 15:09

pcoronel