[Answered ]-Using ManyToManyField through and ensuring DatabaseIntegrity

2👍

Maybe you need to approach it from the other direction to limit the many-to-many relationships. A class (or room, because you can’t use the keyword class as an identifier) can only have one lesson and one teacher, so:

class Room(Model):
    teacher = ForeignKey(Teacher)
    lesson = ForeignKey(Lesson)

A teacher can teach multiple lessons, but only in one room, so this can already be queried from the Room model, e.g.:

Teacher.objects.select_related().values('lesson')

A student can have multiple lessons, rooms and teachers, so there is not way to avoid the many-to-many relationship, but the lessons and teachers are already related by the room, so creating a many-to-many with the room will be the simplest way. This can be done from either side, so the model becomes:

class Room(Model):
    teacher = ForeignKey(Teacher)
    lesson = ForeignKey(Lesson)
    students = ManyToManyField(Student)

Now, ensuring that the teacher and lesson are unique is as simple as adding the appropriate constraint:

class Room(Model):
    teacher = ForeignKey(Teacher)
    lesson = ForeignKey(Lesson)
    students = ManyToManyField(Student)

    class Meta:
        unique_together = ('teacher', 'lesson')

Leave a comment