在django中尝试/除数据库查询

时间:2011-05-11 03:11:06

标签: django django-models

我正在根据数据库中的两个列表检查用户提交的电子邮件地址 - 授权域列表和授权电子邮件地址列表。目前,如果两者均未找到,则会出现DoesNotExist异常。如果两者都找不到,我该如何处理?

以下是我目前在views.py中的代码 -

def register(request):
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            try:
                email_list = EmailList.objects.get(domain=(cd['email'].split('@')[1]))
            except:
                email_list = EmailList.objects.get(email=cd['email'])
            #  I also need another except if neither works for the validator.
            network= Network.objects.get(network=email_list.network)
            User.objects.create(name=cd['name'], email=cd['email'], network=network)
            return HttpResponseRedirect ('/user/view/')
    else:
        form = UserForm()
    return render_to_response('register.html',{'form':form}, context_instance = RequestContext(request))

2 个答案:

答案 0 :(得分:6)

嵌套try / except块。并且不要使用裸except;只捕捉你可以处理的例外。

答案 1 :(得分:3)

您可以嵌套try / except

        try:
            email_list = EmailList.objects.get(domain=(cd['email'].split('@')[1]))
        except:
            try:
                email_list = EmailList.objects.get(email=cd['email'])
            except:
                ...do something else

如果你只是使用这些try / except来做一个简单的测试,那么值得包装try / except:

def get_or_none(model, **kwargs):
    try:
        return model.objects.get(**kwargs)
    except model.DoesNotExist:
        return None

这为您提供了更易读的代码:

if get_or_none(EmailList, domain='domain.com'):
    ...do something
elif get_or_none(EmailList, domain='domain.com'):
    ...do something
else:
    ...do something

As Ignacio mentioned in his answer你应该始终明确,只捕捉你想要的例外。