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

Question:

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?

Asked By: Rhubarb

||

Answers:

You could use count() For example:

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

If the Name column is unique then you could do:

try:
  person = People.objects.get(Name='Fred')
except (People.DoesNotExist):
  # Do something else...

You could also use get_object_or_404() For example:

from django.shortcuts import get_object_or_404
get_object_or_404(People, Name='Fred')
Answered By: tdedecko

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

Answered By: Chase Seibert

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

Answered By: vitorbal

As of Django 1.2 you could use .exists() on a QuerySet, but in previous versions you may enjoy very effective trick described in this ticket.

Answered By: Tuttle

For the sake of explicitness: .exists() is called on a QuerySet and not an object.

This works:

>>> User.objects.filter(pk=12).exists()
True

This does not work:

>>> User.objects.get(pk=12).exists()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'exists'
Answered By: Matt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.