![](/img/trans.png)
[英]Django ManyToMany relationship with abstract base - not possible, but is there a better way?
[英]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
而不出现错误“字段定义与 model '问题'的关系,它要么未安装,要么是抽象的。”
有没有办法让问题子类实例列表不属于“问题”类型? 我希望在测验中同时包含 HTMLQuestion 和 TextQuestions 类型。
当您将问题 model 定义为抽象时,它不会在迁移期间创建表。 抽象 model 允许您重用实现/字段,但不能重用关系。 ManyToMany 字段和 ForeignKey 字段需要一个表来引用。 在您的情况下,您需要通过创建一个类似于 django 在您使用 ManyToMany 字段时为您创建的支持表来手动处理多对多关系。 在您的特定情况下,它应该有四列:
使用q_type获取具体的 model ,您将在其中获取q_id 。
我最终得到的答案是忘记在 Django 中使用 inheritance ,而是将类型放入问题中,然后在问题 Z20F35E630DAF44DBFA4C3F68F5399DC8 本身中创建如何处理该类型的函数。
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)
You could use a concrete base class instead of an abstract one, and have a look at https://django-polymorphic.readthedocs.io/en/stable/ This would return the sub-classed items (plain django returns the base class items , 这不太有用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.