尝试以多对多关系保存对象(多重继承)

时间:2017-07-10 14:35:04

标签: django

我正在为一所教育学校做一个django应用程序,我有一个继承自SchoolClass(非抽象)的两个类(RegularSchoolClass和AdhocSchoolClass)。我有另一个课程(LessonSchedule),它记录课程的每周或每日时间表,并与SchoolClass有多对多的关系。

保存一个正规学校班级后,我试图更新相关课程表(https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/)。

我收到以下错误 - 我认为这是因为LessonSchedule是与SchoolClass而不是RegularSchoolClass的多对多关系?有没有办法使它工作(我不是真的想为RegularSchoolClass和AdhocSchoolClass复制相同的代码)?

ValueError: Cannot add "<RegularSchoolClass: Kindergarten One, Dan, Saturday, 9:00AM - 10:45AM>": the value for field "schoolclass" is None

models.py

class SchoolClass(TimeStampedModel):
    pass

class RegularSchoolClass(SchoolClass):
    def save(self, *args, **kwargs):
        for l in LessonSchedule.objects.filter(lesson_frequency=self.lesson_frequency, start_date=self.start_date):
            l.schoolclass.add(self)

class AdhocSchoolClass(SchoolClass):
    pass

class LessonSchedule(models.Model):
    school_class = models.ManyToManyField(SchoolClass)

1 个答案:

答案 0 :(得分:0)

您必须在您的班级SchoolClass中添加一个田野学校课程

school_class=models.CharField(max_length=some length)