I have a student project relationship. One student can be assigned to only one project. A project can have multiple students
The following is my student and Project model
class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __str__(self):
return self.first_name
class Project(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
How to get create the relationship in this case
CodePudding user response:
Good day!
add following line:
class Project(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Student(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
project = models.ForeignKey(Project, on_delete=models.CASCADE) # This
def __str__(self):
return self.first_name
This way a student can have only one project, project can have many students.