2

I'd like to simply do the following without raising an exception if the item doesn't exist:

User.objects.get(email_address = email_address)

Is there a shortcut for this in Django? I just want to check if a user exists with a given email address.

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
  • 1
    If you actually want to retrieve a single item that may or may not exist, try this [`get_or_none()` pattern](http://stackoverflow.com/questions/1512059/django-get-an-object-form-the-db-or-none-if-nothing-matches). – jathanism Oct 28 '11 at 23:00
  • try [django_annoying](https://bitbucket.org/offline/django-annoying/wiki/Home), supports get_object_or_None and a couple of other fun features... – jawache Oct 29 '11 at 06:10
  • @jawache Thanks, that seems like an awesome library. They should include shortcuts like that in the next release of Django for sure, especially `get_object_or_None`. – Naftuli Kay Oct 30 '11 at 02:46

1 Answers1

3

You could use the queryset method exists().

From the django docs:

exists()
Returns True if the QuerySet contains any results, and False if not.

In your case:

User.objects.filter(email_address=email_address).exists()

If there were more than one user with this email address, exists would still return True, whereas the get() would raise a User.MultipleObjectsTeturned exception.

Alasdair
  • 298,606
  • 55
  • 578
  • 516