I am trying to put together a Django app that will show the teams and games for my fantasy football league. I have taken a few cracks at the models, but I can't get my head wrapped around how they will relate.
This is what I am trying to accomplish:
- Each year, there are six teams that make the "Toilet Bowl" tournament, which will crown the worst team in the league.
- There are three rounds.
- The worst two teams are not playing the first round. That leaves team 1 playing team 4 and team 2 playing team 3.
- In round 2, teams 1 and 2 play the losers from round 1.
- In round 3, the remaining two teams play for the title.
These are the models that I have so far. I know that they're not optimal.
class Owner(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(max_length=100)
phone = models.CharField(max_length=12, null=True)
def __str__(self):
return "%s" % (self.name)
class Team(models.Model):
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Game(models.Model):
year = models.SmallIntegerField(
validators=[MinValueValidator(2010),
MaxValueValidator(2999),
RegexValidator("^(20)([1-5][0-9])$")
])
round = models.SmallIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(3)])
teams = models.ManyToManyField(Team)
#teams = models.ForeignKey(Team, on_delete=models.CASCADE)
#team1_score = models.IntegerField(default=0)
#team2_id = models.ForeignKey(Team, on_delete=models.CASCADE)
#team2_score = models.IntegerField(default=0)
def __repr__(self):
return f"{self.round}, {self.year}, {self.teams}"
I would like to have fields for team scores in the Game model, but with the ManyToManyField type, I am not sure how to reference a team to a score. I am also not crazy about having the round number and year in the Game model, either, but I'm not sure how I'd break them out into their own models and relate them back to Game. I'm also not sure it's standard practice to have a model with only one field (say, Year).
Thanks in advance. This is my first Django app and I've been able to figure most of it out based on searches, but this schema has me stumped.
I'm happy to provide any other information that is needed.
CodePudding user response:
In this case, instead of using a many to many field, you should create a third table that will have as fields the foreign key of the game, the foreign key of the team and the score, remember to define in the Meta the field unique_together so that the keys foreigners are unique together
class GameTeam(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
score = models.PositiveSmallIntegerField()
class Meta:
unique_together = [['game', 'team']]