0

我无法将许多字段保存到数据库中。我有许多“结果价值_#”字段,这些字段是根据我拥有的结果数量生成的。用户选择结果子集(相关结果)并输入相关值。我想将相关值与结果一起保存。到目前为止,我只能硬连线不能解决问题的字段名称。

视图.py

stateoption = get_object_or_404(StateOption, pk=stateoption_id)

if request.method == "POST":
    form = UpdateStateOptionWithOutcomesForm(request.POST, instance=stateoption)
    if form.is_valid():

       cd = form.cleaned_data
       outcomevalue = cd['outcomevalue_1'] #hardwired. This needs to be generalized.        

       for outcome_id in request.POST.getlist('relevantoutcome'):
           stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)

表格.py

class UpdateStateOptionWithOutcomesForm(forms.ModelForm):
    class Meta:
        model = StateOption

    def __init__(self, *args, **kwargs):
       super(UpdateStateOptionWithOutcomesForm, self).__init__(*args, **kwargs)
       self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.all(),required=True, widget=forms.CheckboxSelectMultiple)

       outcome_qs=Outcome.objects.all()
       for outcome in outcome_qs:
           self.fields['outcomevalue_%s' % outcome.pk] = forms.CharField(required=False)

更新

这是我的精简models.py

class StateOptionOutcome(models.Model):
   stateoption = models.ForeignKey(StateOption)
   relevantoutcome = models.ForeignKey(Outcome)
   outcomevalue = models.CharField(max_length=20)

在玩了一些之后,我有类似的东西:

 outcomelist = request.POST.getlist('relevantoutcome')
 for outcome_id in outcomelist:
       cd = form.cleaned_data
       outcomevalue = cd['outcomevalue_%s' % outcomelist[int(outcome_id)]]   

       stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)

但得到错误:

list index out of range

因为它正在获取列表中的值而不是索引位置

4

2 回答 2

0

通过使用解决它:

outcomelist = request.POST.getlist('relevantoutcome')
       for i,outcome_id in enumerate(outcomelist):
           cd = form.cleaned_data
           outcomevalue = cd['outcomevalue_%s' % outcomelist[i]]   

           stateoption_outcome = StateOptionOutcome.objects.create(stateoption=stateoption, relevantoutcome_id=int(outcome_id), outcomevalue=outcomevalue)
于 2013-08-28T20:12:45.047 回答
0

如果我理解正确,那么您正在尝试使用一对一的关系,而应该是一对多的关系。如果您要为一个 StateOption 提供多个 Outcome,我建议您使用多对多桥接表来链接哪个 StateOption 具有哪个 Outcome(s)。然后在该桥接表中,您还可以将关联值存储为相应 StateOption/Outcome 对的附加列。

于 2013-08-28T19:15:20.530 回答