Я не понимаю, почему! Django показывает мне ошибку local 'variable referenced before assignment'?

Я не понимаю почему! Покажите мне эту ошибку local 'variable referenced before assignment' Django? Она работает нормально до HomeTeam, awayTeam, referees, которые я не могу передать в results dict. Я пробовал некоторые решения, например, использовать переменную как GLOBAL, но не получается.

def my_api(request):  
    matches = Matches.objects.all().prefetch_related('score', 'homeTeam', 'awayTeam', 'referees').order_by('-id')

    all_results = []

    for match in matches: # Works fine 
        id = match.id
        utcDate = match.utcDate
        status = match.status
        matchday = match.matchday
        stage = match.stage
        group = match.group
        lastUpdated = match.lastUpdated
        
        for score in match.score.all(): #Works fine
            sco = {}
            sco['winner'] = score.winner
            sco['duration'] = score.duration
            sco['fthomeTeam'] = score.fthomeTeam
            sco['ftawayTeam'] = score.ftawayTeam
            sco['hthomeTeam'] = score.hthomeTeam
            sco['htawayTeam'] = score.htawayTeam
            sco['exthomeTeam'] = score.exthomeTeam
            sco['extawayTeam'] = score.extawayTeam
            sco['phomeTeam'] = score.phomeTeam
            sco['pawayTeam'] = score.pawayTeam
        for homeT in match.homeTeam.all(): # Here is the problem local variable 'hometeams' referenced before assignment
            hometeams = { # i can't pass this variable to result
                'id': homeT.id, 
                'name': homeT.name,
            }
            #hometeams['id'] = homeT.id
            #hometeams['name'] = homeT.name
        for awayT in match.awayTeam.all(): # Here is too problem 
            awayteam = {}
            awayteam['id'] = awayT.id
            awayteam['name'] = awayT.name
        for referees in match.referees.all(): # And here too problem 
            refer = {}
            refer['id'] = referees.id
            refer['name'] = referees.name
            refer['role'] = referees.role
            refer['nationality'] = referees.nationality
    
        result = {
            'id': id,
            'utcDate': utcDate,
            'status': status,
            'matchday': matchday,
            'stage': stage,
            'group': group,
            'lastUpdated': lastUpdated,
            'score': sco,
            'homeTeam': hometeams,# the code works fine till here shows local variable 'hometeams' referenced before assignment          
        }
        all_results.append(result)```

Вернуться на верх