运行 多态关系迁移时 Django 外键不匹配

Django foreign key mismatch when running migrations for polymorphic relationship

我在 Django 应用程序中有以下模型:

class Sender(PolymorphicModel):
    name = models.CharField(max_length=100)
    email = models.EmailField(null=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

class Student(Sender):
    group_name = models.CharField(max_length=100, null=True)

class Teacher(Sender):
    bio = models.TextField(max_length=255, null=True)

class Connection(models.Model):
    student_id = models.ForeignKey('students.Student', null=False, on_delete=models.CASCADE)
    teacher_id = models.ForeignKey('teachers.Teacher', null=False, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

class Message(models.Model):
    body = models.TextField(max_length=255, null=False)
    sender_id = models.ForeignKey('senders.Sender', null=False, on_delete=models.CASCADE)
    connection_id = models.ForeignKey('connections.Connection', null=False, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

Teacher 和 Student 模型 类 都继承自 Sender;我希望 Connection 分别具有指向 Teacher 和 Student 的特定外键。

当我生成和 运行 迁移时,我得到 django.db.utils.OperationalError: foreign key mismatch - "connections_connection" referencing "teachers_teacher".

我是否无法使用从多态模型继承的子模型作为另一个模型的外键?有没有办法解决这个问题,或者我应该使用不同的范例?谢谢!

我自己找到了一种方法,通过删除多态发件人 class 并为消息使用 GenericForeignKey, 但我也很想听听其他方法。

class Student(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    group_name = models.CharField(max_length=100, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

class Teacher(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    bio = models.CharField(max_length=100, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

class Connection(models.Model):
    student_id = models.ForeignKey('students.Student', null=False, on_delete=models.CASCADE)
    teacher_id = models.ForeignKey('teachers.Teacher', null=False, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now_add=True)

class Message(models.Model):
    body = models.TextField(max_length=255, null=False)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    sender_id = models.PositiveIntegerField(null=False)
    content_sender = GenericForeignKey('content_type', 'sender_id')
    connection_id = models.ForeignKey('connections.Connection', null=False, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)