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
JavaScript
x
15
15
1
def CurrentMatch(request, match_id):
2
match = Match.objects.get(id=match_id)
3
match_additional = MatchAdditional.objects.get(match=match)
4
innings = match_additional.current_innings
5
6
recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
7
8
for score in recent:
9
context = {
10
"ball_number": score.ball_number,
11
"over_number": score.over_number,
12
}
13
14
return HttpResponse(json.dumps(context))
15
Advertisement
Answer
You should do something like this :
JavaScript
1
16
16
1
def CurrentMatch(request, match_id):
2
match = Match.objects.get(id=match_id)
3
match_additional = MatchAdditional.objects.get(match=match)
4
innings = match_additional.current_innings
5
6
recent = Score.objects.filter(match=match).filter(innings=innings).order_by('over_number')[::-1][:1]
7
if recent:
8
for score in recent:
9
context = {
10
"ball_number": score.ball_number,
11
"over_number": score.over_number,
12
}
13
return HttpResponse(json.dumps(context))
14
else:
15
return HttpResponse(json.dumps({}))
16