views:

49

answers:

4

What is the accepted way of checking a model's existence in a Django app?

I've seen this method used:

def profile_exists(user):
        try:
                UserProfile.objects.get(user = user)
                return True
        except:
                return False

Is there a built-in function suited for this purpose?

+2  A: 

Bare excepts should not be used. Instead the model's DoesNotExist inner exception or django.core.exceptions.ObjectDoesNotExist should be caught.

Beyond that, either this or using len(SomeModel.objects.filter(...)) are acceptable.

Ignacio Vazquez-Abrams
+1  A: 

That is suitable until the naked except. You always get more than you bargain for with those!

As mentioned by Ignacio Vazquez-Abrams, one should make use of the built in DoesNotExist exception for the model:

def profile_exists(user):
        try:
                UserProfile.objects.get(user = user)
                return True
        except UserProfile.DoesNotExist:
                return False

Presto!

jathanism
+2  A: 

As an additional note, you could make a general purpose function out of it with:

def object_exists(model, **kwargs):
       try:
             model.objects.get(**kwargs)
             return True
       except model.DoesNotExist:
             return False

And then simply call:

profile_exists = object_exists(UserProfile, user=user)
rob boyle
That is a great suggestion!
jathanism
A: 

There's always get_object_or_404, which as its name implies, either returns the object or raises an HttpNotFound error:

from django.shortcuts import get_object_or_404
instance = get_object_or_404(SomeModel, filter_args=whatever)
Daniel Roseman