简体   繁体   English

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

[英]django - how to check if model is empty

I have settings form page. 我有设置表单页面。 If user filled the form once; 如果用户填写一次表格; it must display those values. 它必须显示这些值。 But if there is no data [first time] I get query error. 但是,如果没有数据[第一次],则会出现查询错误。 I need that query, because the form data must be written as related with current user [logged in]. 我需要该查询,因为必须将表单数据写为与当前用户[已登录]相关。

here is my view part : 这是我的观点部分:

@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))

I think I need to check the model and if it is empty I should do something different. 我认为我需要检查模型,如果模型为空,我应该做些不同的事情。

I am stuck. 我被困住了。

Thank you 谢谢

You want to make use of the .exists() queryset option 您想使用.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))

see QuerytSet API reference for more information 有关更多信息,请参见QuerytSet API参考

You just need to wrap that get query in try ... except and set instance to none, like this. 您只需要在try ... except包装该get查询,并将实例设置为none,就像这样。

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))

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

Profile.objects.get_or_create(owner__username = username)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM