Alex Peniz
Alex Peniz

Reputation: 483

Django search for child models via foreign key

I have a models.py file that more or less looks like this:

class Match(models.Model):
    match_id = models.BigIntegerField()

class Team(models.Model):
    team_id = models.CharField(max_length=4)
    match = models.ForeignKey(
        Match,
        related_name='teams',
        on_delete=models.CASCADE,
    )
    win = models.BooleanField()

class Player(models.Model):
    player_id = models.IntegerField()
    team = models.ForeignKey(
        Team,
        related_name='players'
        on_delete=models.CASCADE,
    )

For each match, I want to find the two teams that played, and for each team, I want to find the players that were on the team. This is what I tried so far:

match_id = 123456789
match_info = Match_model.objects.get(match_id=match_id)

red_info = Team_model.objects.get(match=match_info, team_id='Red')
blue_info = Team_model.objects.get(match=match_info, team_id='Blue')

red_players = Player_model.objects.filter(team=red_info)
blue_players = Player_model.objects.filter(team=blue_info)

but Django is giving me the error:

Team matching query does not exist. 

How would I go about fixing this error? Any pointers on how to correct my queries would be greatly appreciated!

Upvotes: 0

Views: 41

Answers (1)

yanqzhi
yanqzhi

Reputation: 412

try:
    red_info = Team_model.objects.get(match=match_info, team_id='Red')
    blue_info = Team_model.objects.get(match=match_info, team_id='Blue')
except Team_model.DoesNotExist:
    pass
else:
    red_players = Player_model.objects.filter(team=red_info)
    blue_players = Player_model.objects.filter(team=blue_info)

Upvotes: 1

Related Questions