Reputation: 1709
I have the following models:
class Course(models.Model):
Name = CharField(max_length=32, unique=True,)
class Tutorial(models.Model):
Name = CharField(max_length=64, unique=True,)
Courses = ManyToManyField(Course,)
Index = PosSmallInt()
There are many Course
s and every Course
has Tutorial
s, but there are some Course
s that share the same Tutorial
s.
Now, every Tutorial
should have a unique Index
in the Course
that it's inside of.
I think I should point out that the Courses
(ManyToManyField
) was a regular Course
(ForeignKey
) not long ago, which means I had duplicate Tutorial
s, and I had this line in the Meta
class of Tutorial
:
unique_together = (('Course', 'Index'))
to keep Course
from having different Tutorial
s in the same Index
.
But now that it's a ManyToManyField
it's not possible.
Example:
I have the following Course
s with their Tutorial
s:
(For the sake of the example please consider "Conditions" and "Loops" to have the exact same information.)
How can I have same Tutorial
s in different Course
s with different Index
es?
Upvotes: 0
Views: 25
Reputation: 252
Try with through
attribute:
class Tutorial(models.Model):
Name = CharField(max_length=64, unique=True,)
Courses = ManyToManyField(Course, through='TutorialCourse')
class TutorialCourse(models.Model):
tutorial = models.ForeignKey(Tutorial, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
Index = PosSmallInt()
class Meta:
unique_together = (('tutorial', 'course', 'Index'))
Upvotes: 2