python - 具有 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 类型。
解决方案
当您将 Question 模型定义为 abstract 时,它不会在迁移期间创建表。抽象模型允许您重用实现/字段,但不能重用关系。ManyToMany 字段和 ForeignKey 字段需要一个表来引用。在您的情况下,您需要通过创建一个类似于 django 在使用 ManyToMany 字段时为您创建的支持表来手动处理多对多关系。在您的特定情况下,它应该有四列:
- 身份证(汽车),
- 测验(foreign_key),
- q_type(如果对于您从问题派生的每种类型),
- q_id(保存您所引用记录的 id 的整数)。
使用q_type获取您将获得q_id的具体模型。
推荐阅读
- html - 为另一个图像设置背景图像?
- python-3.x - 在 django views.py 中获取 NameError,因为 NameError : name 'edit_load_table' is not defined
- c++ - 如何在没有朋友c ++的情况下进行模板分配
- html - 无法从 Excel 单元格复制 URL 并将其发送到网页
- css - SVG 背景图像仅在 Chrome 上不清晰(在 Firefox 和 Safari 上显示正确)
- javascript - 使用 loadModules ReactJS 访问 esri 事件中的状态
- css - TSX 组件中样式标记中 CSS 的语法突出显示
- php - PHP - 仅在 txt 文件中找到匹配项时追加
- typescript - 反应导航抽屉加倍URI参数
- c - 我的 Makefile 中没有发生链接;返回'未定义的对'main'的引用