django - 获取相关的子类对象

时间:2013-12-05 18:26:07

标签: python django

构建自定义表单应用程序我得到以下models.py

#models.py
class Question(models.Model):
    question_title = models.TextField(...)


class Answer(models.Model):
    answer_title = models.TextField(...)
    question = models.ForeignKey(Question)

    class Meta:
        abstract = True


class BoolAnswer(Answer):
    result = models.BooleanField(...)
    if_answer = models.TextField(...)
    else_answer = models.TextField(...)

class NumberAnswer(Answer):
    answer = models.DecimalField(...)

class MultipleChoiceAnswer(...):
    ....

现在我试图使用以下方法获得属于一个问题的所有答案:

question.answer_set.all()

不存在。只有

question.boolanswer_set
question.numberanswer_set
....

是否有一种优雅的方式来获得所有答案?

1 个答案:

答案 0 :(得分:0)

正如@TimmyO'Mahony所说:一个人需要

https://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager

以下代码有效:(thx @kathikr):

class Answer(models.Model):
    answer_title = models.TextField(...)
    question = models.ForeignKey(Question, related_name='answer_set')

    class Meta:
        abstract = True

    objects = InheritanceManager()

现在question.answer_set.all()获取所有答案子类对象