views:

100

answers:

4

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?

A: 

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')
tdedecko
+4  A: 

An exists() method was just added in Django 1.2, which was released today.

Chase Seibert
+5  A: 

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

vitorbal
A: 

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

Tuttle