笔记:django get方法的异常

.
.
.
if num == 1:
return clone._result_cache[0]
if not num:
raise self.model.DoesNotExist(
"%s matching query does not exist." %
self.model._meta.object_name
)
raise self.model.MultipleObjectsReturned(
"get() returned more than one %s -- it returned %s!" %
(self.model._meta.object_name, num)
)
.
.
.
以上代码截自query.py中的get方法
可见
当取不到记录时抛出 模型类名.DoesNotExist异常
当取到多条记录时抛出 模型类名.MultipleObjectsReturned异常

def post(self,request):
depname = request.POST.get('depname')
parentdepid = request.POST.get('seldep')
if not depname:
return render(request, 'depinfo.html', {'err': '部门名称不能为空'})
try:
parentdep = models.Dept.objects.get(id=parentdepid)
except models.Dept.DoesNotExist:
dep = models.Dept.objects.create(depname=depname)
else:
dep = models.Dept.objects.create(depname=depname,parentdep=parentdep)
return redirect(reverse('user:adddep'))
posted @ 2020-07-31 10:06  大牛等等我  阅读(1535)  评论(0编辑  收藏  举报