【发布时间】:2017-07-07 07:38:50
【问题描述】:
我正在尝试构建两个名为 SurveyQuestionBase 和 SurveyResponseBase 的抽象类,它们将作为模板快速定义新的具体模型,以在我们的网站上实施特定调查。我遇到的问题是强制SurveyResponseBase 模型在具体化时应将ForeignKey 定义为SurveyQuestionBase 的具体模型。
Django 不允许我们将ForeignKeys 定义为抽象类,所以我不能,例如,这样做:
question = models.ForeignKey(SurveyQuestionBase)
出于类似的原因,我也不能将其命名为 None 或 app_label.ModelName。
一个 hacky 解决方法是创建一个新的具体模型 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
【问题讨论】:
标签: python django django-models metaprogramming django-orm