0
votes

I'm creating a model in Django with 2 main classes - a match class and a player class. Each match needs to have 2 players taken from the database, so I've included foreign keys to the table, but these are clashing since I'm referencing the player class twice in the match class.

I've tried using the related_name field to prevent these clashes, as seen in the code below. While this example seems to work for other users here, I'm getting a name error, stating that the name declared in related_name is not defined. Changing the value of related_name changes the error content.

class Player(models.Model):
    p_pub_date = models.DateTimeField('date published')
    p_username = models.CharField(max_length=20)
    p_tag = models.CharField(max_length=20)
    p_league_id = models.ForeignKey(League, on_delete=models.CASCADE)
    p_elo_rating = models.IntegerField(default=1200)
    p_glicko_rating = models.IntegerField(default=1200)
    p_character = models.CharField(max_length=20)
    p_country = models.CharField(max_length=50)

class Match(models.Model):
    m_pub_date = models.DateTimeField('date published')
    m_tournament_id = models.ForeignKey(Tournament, on_delete=models.CASCADE)
    m_player0_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name=m_player0_id)
    m_player1_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name=m_player1_id)
    m_result = models.IntegerField(default=0)

When I run makemigrations I get an error in my models.py file: m_player0_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name=m_player0_id) NameError: name 'm_player0_id' is not defined

Thanks in advance

1

1 Answers

3
votes

you need to use quotes

m_player0_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='m_player0_id')
m_player1_id = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='m_player1_id')

also I would choose a different related name, like 'matches_as_p1' 'matches_as_p2' maybe