django - 如何检查模型是否为空

时间:2012-09-22 13:10:49

标签: django django-models django-views

我有设置表单页面。如果用户填写表格一次;它必须显示这些值。但如果没有数据[第一次]我收到查询错误。我需要该查询,因为表单数据必须与当前用户[登录]相关联。

这是我的观点部分:

@login_required(login_url='/login/')
def profile_page(request,username):
    query = Profile.objects.get(owner__username = username) ##error!
    if request.method == 'POST':
        form = profile_form(request.POST,instance=query)
        form.save()
        return HttpResponseRedirect('/admin/')
    else:
        form = profile_form(instance=query)


    return render_to_response('profile_save.html',{'form':form},context_instance = RequestContext(request))

我想我需要检查模型,如果它是空的,我应该做一些不同的事情。

我被困住了。

谢谢

3 个答案:

答案 0 :(得分:3)

您想要使用.exists() queryset选项

@login_required(login_url='/login/')
def profile_page(request,username):
    form = profile_form()
    if Profile.objects.get(owner__username = username).exists():
        query = Profile.objects.get(owner__username = username)
        if request.method == 'POST':
            form = profile_form(request.POST,instance=query)
            form.save()
            return HttpResponseRedirect('/admin/')
        else:
            form = profile_form(instance=query)

    return render_to_response('profile_save.html',{'form':form},context_instance = RequestContext(request))

有关详细信息,请参阅QuerytSet API reference

答案 1 :(得分:0)

您只需要在get中包装try ... except查询,并将实例设置为无,就像这样。

from django.core.exceptions import ObjectDoesNotExist
@login_required(login_url='/login/')
def profile_page(request,username):
    try:
        query = Profile.objects.get(owner__username = username)

    #to be more specific you can except ProfileObjectDoesNotExist
    except ObjectDoesNotExist: 
        query = None  #Doesn't exist, set to None

    if request.method == 'POST':
        form = profile_form(request.POST,instance=query)
        form.save()
        return HttpResponseRedirect('/admin/')
    else:
        form = profile_form(instance=query)

    return render_to_response('profile_save.html',{'form':form},
                              context_instance = RequestContext(request))

答案 2 :(得分:0)

我想我可能已经为此目的使用了get_or_create。

Profile.objects.get_or_create(owner__username = username)