首页 > 解决方案 > 具有 ManyToMany 的 django 抽象基类

问题描述

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如果没有错误“字段定义与模型‘问题’的关系,要么未安装,要么是抽象的。”我无法运行。

有没有办法让问题子类实例列表不属于“问题”类型?我希望在测验中同时包含 HTMLQuestion 和 TextQuestions 类型。

标签: pythondjangosubclass

解决方案


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

  • 身份证(汽车),
  • 测验(foreign_key),
  • q_type(如果对于您从问题派生的每种类型),
  • q_id(保存您所引用记录的 id 的整数)。

使用q_type获取您将获得q_id的具体模型。


推荐阅读