What is the accepted way of checking a model's existence in a Django app?
I've seen this method used:
def profile_exists(u开发者_开发知识库ser):
try:
UserProfile.objects.get(user = user)
return True
except:
return False
Is there a built-in function suited for this purpose?
Bare except
s 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.
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)
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!
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)
精彩评论