UnboundLocalError:赋值前引用的局部变量'toto'

时间:2016-11-29 08:33:47

标签: django

我在Django时遇到错误,但我找不到解决方案:

  

/ Identity / recherche局部变量'toto'中的UnboundLocalError   在分配前引用

这是我脚本的一部分:

def Consultation(request) :

    identity = Identity.objects.all().order_by("-id")[:10] #Les 10 dernières fiches créées
    identity_France = Identity.objects.filter(country='64').order_by("-id")[:10] #Les 10 dernières fiches où la personne habite en France

    query = request.GET.get('q')
    if query :
        toto = Identity.objects.filter(lastname__icontains=query)        

    context = {
        "identity" : identity,
        "identity_France" : identity_France,
        "query" : query,
        "toto" : toto,
        }

    return render(request, 'resume.html', context)

非常感谢你:)

1 个答案:

答案 0 :(得分:1)

如消息所示,toto未定义。

query = request.GET.get('q')
if query :
    toto = Identity.objects.filter(lastname__icontains=query)        
else :
    toto = []

或者可能稍微更加pythonic

try:
   query = request.GET['q']
   toto = Identity.objects.filter(lastname__icontains=query)        
except KeyError:
   toto = []
   query = None