Eyal
Eyal

Reputation: 1709

ManyToManyField along with different additional value for each

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 Courses and every Course has Tutorials, but there are some Courses that share the same Tutorials.

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 Tutorials, and I had this line in the Meta class of Tutorial:

unique_together = (('Course', 'Index'))

to keep Course from having different Tutorials in the same Index.

But now that it's a ManyToManyField it's not possible.

Example:

I have the following Courses with their Tutorials:

(For the sake of the example please consider "Conditions" and "Loops" to have the exact same information.)

How can I have same Tutorials in different Courses with different Indexes?

Upvotes: 0

Views: 25

Answers (1)

Gil Guilherme
Gil Guilherme

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

Related Questions