50

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?

user2291758
  • 715
  • 8
  • 19
Rhubarb
  • 3,893
  • 6
  • 41
  • 55
  • Possible duplicate of [what is the right way to validate if an object exists in a django view without returning 404?](http://stackoverflow.com/questions/639836/what-is-the-right-way-to-validate-if-an-object-exists-in-a-django-view-without-r) – Wtower Apr 17 '17 at 19:40

5 Answers5

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

vitorbal
  • 2,871
  • 24
  • 24
  • When you have really big tables I wouldn't recommend doing a count() on them, because that can take quite some time to find all the matches (in vain, when you only are interested if knowing if there is at least one). If I had to do this, I'd do a select with a limit 1. It will still take a lot of time if there were no matches (worst case scenario), but it will finish a zillion times quicker if any record is actually found. Note: this comment was meant for the proposed count() alternative. I see a recommendation to use exists() in the update, which I agree would be the actual way to go. – drakorg Mar 31 '18 at 18:46
47

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

eykanal
  • 26,437
  • 19
  • 82
  • 113
Chase Seibert
  • 15,703
  • 8
  • 51
  • 58
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')
tdedecko
  • 1,442
  • 10
  • 15
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.

Harmlezz
  • 7,972
  • 27
  • 35
Tuttle
  • 160
  • 1
  • 7
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'
Matt
  • 133
  • 1
  • 6