如何在django中使用forloop解决局部变量错误?

How to solve local variable error with forloop in django?

信息:我想从上下文中获取数据。上下文数据来自 for 循环函数。

问题:我得到这个UnboundLocalError local variable 'context' referenced before assignment

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]

    for score in recent:
        context = {
            "ball_number": score.ball_number,
            "over_number": score.over_number,
        }

    return HttpResponse(json.dumps(context))

它发生是因为最近的查询集是空的。使用此代码段:

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
    if len(recent) > 0:
        for score in recent:
            context = {
                "ball_number": score.ball_number,
                "over_number": score.over_number,
            }
        return HttpResponse(json.dumps(context))
    else:
        return HttpResponse(json.dumps({}))

通过这部分代码len(recent)您可以检查查询集是否有对象。

你应该这样做:

def CurrentMatch(request, match_id):
    match = Match.objects.get(id=match_id)
    match_additional = MatchAdditional.objects.get(match=match)
    innings = match_additional.current_innings

    recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
    if recent:
        for score in recent:
            context = {
                "ball_number": score.ball_number,
                "over_number": score.over_number,
            }
        return HttpResponse(json.dumps(context))
    else:
        return HttpResponse(json.dumps({}))