Django 抽象基础 class 与 ManyToMany

django abstract base class with ManyToMany

class Question(models.Model):
    answer_choices = models.ManyToManyField(Answers)

    class Meta:
        abstract = True

class HTMLQuestion(Question):
    question = models.fields.TextField()

class TextQuestion(Question):
    question = models.fields.TextField()

class Quiz(models.Model):
    questions = models.ManyToManyField(Question)

最后一行无效。我不能 运行 python manage.py makemigrations 没有错误“字段定义与模型 'Question' 的关系,它要么未安装,要么是抽象的。”

有没有一种方法可以得到一个 Question 子类实例列表,而无需将其设为“Question”类型?我想让 HTMLQuestion 和 TextQuestions 两种类型都出现在测验中。

当您将问题模型定义为抽象时,它不会在迁移期间创建 table。抽象模型允许您重用 implementation/fields,但不能重用关系。 ManyToMany 字段和 ForeignKey 字段需要一个 table 来引用。在您的情况下,您需要通过创建一个类似于 django 在您使用 ManyToMany 字段时为您创建的支持 table 来手动处理多对多关系。在您的特定情况下,它应该有四列:

  • id(自动),
  • 测验(foreign_key),
  • q_type(如果对于您从 问题),
  • q_id(保存您所在记录 ID 的整数 参考)。

使用 q_type 获取具体模型,您将在其中获得 q_id.

我最终得到的答案是忘记在 Django 中使用继承,而是将类型放在问题中,然后在问题模型本身中创建如何处理该类型的函数。

class Question(models.Model):
    answer_choices = models.ManyToManyField(Answers)
    question_type = models.fields.TextField() # "htmlquestion", "textquestion"
    
    def how_to_deal_with_type(question_type):
        # code here

class Quiz(models.Model):
    questions = models.ManyToManyField(Question)