django inline modelform外键相关值

时间:2016-09-14 20:07:35

标签: python django django-1.8 inline-formset

我刚开始玩django。我在这里阅读了文档和类似的问题,但我找不到解决方案,可能是我错过了一些非常明显或以错误的方式解决问题的方法

我有以下型号:

class Interview(models.Model):  
    nickname  = models.CharField(max_length=25, null=False, blank=False)

class Question(models.Model):
    phrase = models.CharField(max_length=200, null=False, blank=False)

class Answer(models.Model): 
    [...]
    interview = models.ForeignKey(Interview,on_delete=models.CASCADE, null=False)  
    question = models.ForeignKey(Question,on_delete=models.DO_NOTHING, null=False)
    code = models.CharField( max_length=1, choices=CODE_CHOICES, null=True)

问题中的短语字段可能包含“*”,在显示问题时,我希望将其替换为访谈的昵称。

在视图中显示结果很简单:

answers = Answer.objects.filter(interview=interview_obj)
for a in answers:
    a.question.phrase = a.question.phrase.replace('*',a.interview.nickname)
return render(request, 'results.html', {'answers': answers })

无论如何,我无法对formset做同样的事情。以下显然不起作用,但我没有找到实现我想要的方法:

class AnswerForm(ModelForm):
    code = ChoiceField(widget=RadioSelect(renderer=HorizontalRadioRenderer,attrs={'required': 'true'}), choices=Answer.CODE_CHOICES)

    class Meta:
        model = Answer
        fields = ['code']

在视图中:

AnswerFormset = inlineformset_factory(Question,Answer,form=AnswerForm,fields=['code'],extra=0)
answer_list = Answer.objects.filter(interview=interview_obj)
for a in answers:
    a.question.phrase = a.question.phrase.replace('*',a.interview.nickname)
formset = AnswerFormset(queryset=answer_list)
return render(request, 'interview.html', { 'formset' : formset, })

0 个答案:

没有答案