0

I have the following models

from django.db import models

class league(models.Model):
name = models.CharField(max_length=64)

def __str__(self):
    return f"{self.name}"

class player(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=128)
age = models.IntegerField()
position = models.CharField(max_length=1)
nteam = models.CharField(max_length=128)

def __str__(self):
    return f"{self.id} {self.name} {self.age} {self.position} {self.nteam}"

class team(models.Model):
name = models.CharField(max_length=64)
league = models.ForeignKey(league, null=True, blank=True, on_delete=models.CASCADE, related_name="teams")
roster = models.ManyToManyField(player, blank=True, related_name="rosters")

def __str__(self):
    return f"{self.name} {self.league}"

My goal would be to have many different leagues, each league containing multiple teams. I want a player only to be added to one team in a league. Right now I created a league, add several teams, then added players to each team. As of now I can take a player and add to all the teams in the same league if I want. How would you add a constraint so that once a player has been added to a team, they can no longer be added to another team in the same league?

Kripke
  • 1
  • 2
  • Does this answer your question? [Django Unique Together (with foreign keys)](https://stackoverflow.com/questions/4440010/django-unique-together-with-foreign-keys) – Iain Shelvington Jan 31 '21 at 05:38
  • I was looking at the following https://stackoverflow.com/questions/56024059/django-uniqueconstraint I think the Unique Together is an older way of doing it. – Kripke Jan 31 '21 at 14:48
  • I tried adding the following code to the end of the model 'class Meta: constraints = [ models.UniqueConstraint(fields=['league', 'roster'], name='unique teams') ]' But I am getting an error when I migrate FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: Newteam has no field named 'roster' – Kripke Jan 31 '21 at 17:29

0 Answers0