Harry Hartley
Harry Hartley

Reputation: 85

Django: Adding 2 foreign keys referencing the same table using related_name causing NameError - value given to related name is not defined

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

Upvotes: 2

Views: 1992

Answers (1)

Daniele Bernardini
Daniele Bernardini

Reputation: 1536

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

Upvotes: 5

Related Questions