我试图有一组带有个人答案的问题,每个用户都可以回答。为了实现这种功能,我构建了以下模型:
模型.py:
class Question(models.Model):
question = models.TextField(null=False)
class PossibleAnswer(models.Model):
question=models.ForeignKey(Question, related_name="possible_answer")
answer = models.CharField(max_length=200)
class Answer(models.Model):
question = models.ForeignKey(Question)
user = models.ForeignKey(User)
real_answer = models.ForeignKey(PossibleAnswer, related_name="real_answer")
最初,管理界面就足够了,可以解决这些问题。它应该在“每个问题”的基础上可见,因此“问题”应该显示它允许的答案以及用户可以给出的答案:
管理员.py:
class AnswerInline(admin.TabularInline):
model = Answer
class PossibleAnswerInline(admin.TabularInline):
model = PossibleAnswer
class QuestionAdmin(admin.ModelAdmin):
inlines = [PossibleAnswerInline, AnswerInline]
admin.site.register(Question, QuestionAdmin)
一切都很好,直到我保存答案,这会产生一个 IntegrityError。我相信这与对象之间的依赖关系有关?
我无法解决的第二项:为了将 real_answer 的选择限制为实际选项(与问题相关),我在 forms.py 中定义了以下内容:
class AnswerForm(ModelForm):
class Meta:
model = Answer
def __init__(self, *args, **kwargs):
super(AnswerForm, self).__init__(*args, **kwargs)
choices = self.instance.question.possible_answer.all()
self.fields["real_answer"].choices = choices
并在 admin.py 中使用它,如下所示:
class AnswerInline(admin.TabularInline):
model = Answer
form = AnswerForm
当我运行它时, self.instance.question.possible_answer.all()总是引发 DoesNotExist
任何指针都非常感谢。
最好的,
安德烈亚斯