Skip to content
Advertisement

How to solve local variable error with forloop in django?

Info: I want to get data from context. The context data is coming from for loop function.

Problem: I am getting this 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))

Advertisement

Answer

You should do something like this :

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({}))
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement