我试图建立两个抽象类称为SurveyQuestionBase
和SurveyResponseBase
,将作为模板来快速确定新的具体型号我们的网站上实施具体的调查。我遇到的问题是强制执行SurveyResponseBase
模型,具体时应将ForeignKey
定义为SurveyQuestionBase
的具体模型。定义有一个ForeignKey的抽象模型到另一个抽象模型
Django不允许我们定义ForeignKeys
抽象类,所以我没有,比如,这样做可以: question = models.ForeignKey(SurveyQuestionBase)
无论是我可以把它作为None
或app_label.ModelName
出于同样的原因。
一个诡异的问题是创建一个新的具体模型SurveyQuestionConcrete
并使ForeignKey
指向这个:question = models.ForeignKey(concrete_model)
,并结合验证以确保此模型被替换。
有没有更简单的方法来实现同样的目标? 所有我需要做的是确保当有人从SurveyResponseBase
定义了一个具体的模型,他们包括ForeignKey
从SurveyQuestionBase
这里定义的具体模型的完整代码:
from __future__ import unicode_literals
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
# Implementation borrows from: https://github.com/jessykate/django-survey/
class SurveyQuestionBase(models.Model):
TEXT = 'text'
INTEGER = 'integer'
RADIO = 'radio'
SELECT = 'select'
MULTI_SELECT = 'multi-select'
ANSWER_TYPE_CHOICES = (
(INTEGER, 'Integer',),
(TEXT, 'Text',),
(RADIO, 'Radio',),
(SELECT, 'Select',),
(MULTI_SELECT, 'Multi-Select',),
)
question = models.TextField()
required = models.BooleanField()
question_type = models.CharField(choices=ANSWER_TYPE_CHOICES, max_length=20)
class Meta:
abstract = True
class SurveyResponseBase(models.Model):
"""
concrete_question_model: 'app_label.Model' - Define the concrete model this question belongs to
"""
concrete_model = 'SurveyQuestionBase'
question = models.ForeignKey(concrete_model)
response = models.TextField()
class Meta:
abstract = True