Skip to content

Instantly share code, notes, and snippets.

@heath
Last active August 29, 2015 14:05
Show Gist options
  • Save heath/d51b26002d14541f0280 to your computer and use it in GitHub Desktop.
Save heath/d51b26002d14541f0280 to your computer and use it in GitHub Desktop.
"""
Create a Many­to­Many relationship
Create two models connected by a many­to­many relationship.
Model 1:
Campus
city
state
name
Model 2:
Student
first name
last name
Bearing in mind that a student can belong to more than one campus,
set up their relationship with an additional field denoting if a
particular campus is their primary campus.
"""
class Campus(models.Model):
students = models.ManyToManyField(Student)
city = models.CharField(max_length=30)
name = models.CharField(max_length=30)
state = models.CharField(max_length=2)
def __repr__(self):
return repr({
"city": self.city,
"name": self.name,
"state": self.state
})
class Student(model.Model):
primary_campus = models.ForeignKey(Campus)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
def __str__(self):
return self.first_name + self.last_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment