Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For Django models, is there a shortcut for seeing if a record exists?

Say I have a table People, is there a way to just quickly check if a People object exists with a name of 'Fred'? I know I can query

People.objects.filter(Name='Fred') 

and then check the length of the returned result, but is there a way to do it in a more elegant way?

like image 765
Rhubarb Avatar asked May 18 '10 01:05

Rhubarb


People also ask

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

What is Q used for in Django?

Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects we can make complex queries with less and simple code.

What does .values do in Django?

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.


2 Answers

Update:

As mentioned in more recent answers, since Django 1.2 you can use the exists() method instead (link).


Original Answer:

Dont' use len() on the result, you should use People.objects.filter(Name='Fred').count(). According to the django documentation,

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

source: Django docs

like image 112
vitorbal Avatar answered Oct 02 '22 05:10

vitorbal


An exists() method in the QuerySet API is available since Django 1.2.

like image 20
Chase Seibert Avatar answered Oct 02 '22 03:10

Chase Seibert