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?
Bare
excepts should not be used. Instead the model’sDoesNotExistinner exception ordjango.core.exceptions.ObjectDoesNotExistshould be caught.Beyond that, either this or using
len(SomeModel.objects.filter(...))are acceptable.