我有兩個模型是老師和學生。我還有另外兩個模型,一堂課和一堂課,其中課程是實際的課題,而課堂則用來劃分學生。我想創建以下關係。使用ManyToManyField並確保DatabaseIntegrity
A teacher teaches a specific lesson in a specific class e.g Mike teaches python in C3
和
A student attends a class with a specific lesson e.g George is taking Python in C3
所以eventualy
George is Mike's student in python in C3
我用使用中間模型在兩個模型中一個多對多字段。很多很多,因爲老師可以有很多類,在那裏他可以教很多教訓,一類可能有許多教師的教學不同的經驗教訓(同爲學生)
,所以我做了以下內容:
class Teacher(models.Model):
teaches = models.ManyToManyField(Class, through=TeacherTeaches)
class TeacherTeaches(models.Model):
teacher = models.ForeignKey(Teacher)
class = models.ForeignKey(Class)
lesson = models.ForeignKey(Lesson)
和學生:
class Student(models.Model):
attends = models.ManyToManyField(Class, through=StudentAttends)
class StudentAttends(models.Model):
student = models.ForeignKey(Student)
class = models.ForeignKey(Class)
lesson = models.ForeignKey(Lesson)
但我認爲它不能與這個實現做的是確保了同樣的問題不是由兩個不同的教師,正確在同一類教因爲ForeignKey的的(?我認爲)。有沒有更好的方法來「建立」我的模型來實現上述行爲?我應該「團結」兩種中間模式嗎?