Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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({}))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading