通过现有的中介(数据透视)表创建多对多关系

时间:2019-04-27 10:25:25

标签: django foreign-keys

我在数据库上有一些表,并尝试使用Django创建API包装器。我要介绍的资源之一是老师及其相关课程。

这些表中存储的数据:

教授:

ProfessorUserId | ProfessorCode | ...

TermLessons :(对数据进行分类)

TermLessonId | ExamDate | ...

教授课程:(数据透视表)

ProfessorUserId | TermLessonId | ...

我为教师和班级设计了模型,然后定义了如下的多对多关系:

class Teacher(models.Model):
    ProfessorUserId = models.CharField(max_length=255, primary_key=True)
    ProfessorCode = models.CharField(max_length=255)

    class Meta:
        db_table = "[Education].[Professors]"


class Class(models.Model):
    TermLessonId = models.CharField(max_length=255, primary_key=True)
    teacher = models.ManyToManyField(
        Teacher,
        related_name='RelatedClasses',
        through='ProfessorLessons',
        through_fields=('TermLessonId', 'ProfessorUserId')
    )

    class Meta:
        db_table = "[Education].[TermLessons]"


class ProfessorLessons(models.Model):
    TermLessonId = models.ForeignKey(Class, on_delete=models.CASCADE, to_field='TermLessonId')
    ProfessorUserId = models.ForeignKey(Teacher, on_delete=models.CASCADE, to_field='ProfessorUserId')

    class Meta:
        db_table = "[Education].[ProfessorLessons]"

尽管在尝试获取类似以下内容的相关结果时,我为所有模型定义了主键:Teacher.objects.filter(ProfessorCode=' some code ').first().relatedClasses.all()我收到此错误消息:

('42S22',“ [42S22] [Microsoft] [用于SQL Server的ODBC驱动程序13] [SQL Server]无效的列名'TermLessonId_id'。(207)(SQLExecDirectW); [42S22] [Microsoft] [ODBC驱动程序13对于SQL Server] [SQL Server]无效的列名'ProfessorUserId_id'。(207)“)

0 个答案:

没有答案