【问题标题】:Convention for checking the existence of a Django model?检查 Django 模型是否存在的约定?
【发布时间】:2010-02-06 01:06:32
【问题描述】:
在 Django 应用程序中检查模型是否存在的公认方法是什么?
我见过这种方法:
def profile_exists(user):
try:
UserProfile.objects.get(user = user)
return True
except:
return False
是否有适合此目的的内置函数?
【问题讨论】:
标签:
python
django
django-models
【解决方案1】:
不应使用裸excepts。而是模型的DoesNotExist 内部异常或django.core.exceptions.ObjectDoesNotExist should be caught。
除此之外,无论是这个还是使用len(SomeModel.objects.filter(...))都是可以接受的。
【解决方案2】:
作为附加说明,您可以使用以下方法制作通用功能:
def object_exists(model, **kwargs):
try:
model.objects.get(**kwargs)
return True
except model.DoesNotExist:
return False
然后简单地调用:
profile_exists = object_exists(UserProfile, user=user)
【解决方案3】:
那是适合直到赤裸裸的except。你总是得到比你讨价还价的更多!
正如Ignacio Vazquez-Abrams 所提到的,应该利用模型内置的DoesNotExist 异常:
def profile_exists(user):
try:
UserProfile.objects.get(user = user)
return True
except UserProfile.DoesNotExist:
return False
快!
【解决方案4】:
总是有get_object_or_404,顾名思义,要么返回对象,要么引发HttpNotFound错误:
from django.shortcuts import get_object_or_404
instance = get_object_or_404(SomeModel, filter_args=whatever)