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

50πŸ‘

βœ…

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

47πŸ‘

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

11πŸ‘

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')

8πŸ‘

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.

0πŸ‘

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'

Leave a comment