我試圖建立兩個抽象類稱爲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