Search code examples
djangomodels

django models field relation on it itself


I can't decide which is best way to relate django models field with it own other field. I have Match class which possess field teams(m-t-m filed on other model) and i need to store match result with corresponding score for each team. It can be only 2 team in one match.

class Match(models.Model):
 teams = models.ManyToManyField(Team)
 tournament = models.ForeignKey(Tournament)
 match_round = models.ForeignKey(Round)
 team_1_hit = models.IntegerField(default=0)
 team_2_hit = models.IntegerField(default=0)

Solution

  • It's okay to have two ForeignKey fields in this situation. ManyToManyField could cause errors, when 3 teams will be added. So you could specify two ForeignKey fields with related_name:

    class Match(models.Model):
        team1 = models.ForeignKey('Team', related_name='team1')
        team2 = models.ForeignKey('Team', related_name='team2')
        tournament = models.ForeignKey(Tournament)
        match_round = models.ForeignKey(Round)
        team_1_hit = models.IntegerField(default=0)
        team_2_hit = models.IntegerField(default=0)