0

我正在使用ModelFormsModelMultipleChoiceField部件。我有两个问题:

  1. 我的“治疗选项”复选框小部件从我的数据库中SelectOptionForStateForm的表中呈现现有选择。stateoption它如何知道在该表中查找现有记录?在我的views.py 中,我只传递了不看表格的disease和对象。statestateoption

  2. 如何实例化我的SelectOutcomeForOptionForm,以便我的治疗结果复选框也从stateoptionoutcome我的数据库中的表中预先选择?

表格.py

class SelectOptionForStateForm(forms.ModelForm):
    class Meta:
       model = State
       exclude = ['state', 'relevantdisease']

    def __init__(self, *args, **kwargs):
       disease=kwargs.pop('disease', None)
       super(SelectOptionForStateForm, self).__init__(*args, **kwargs)
       self.fields['relevantoption']=forms.ModelMultipleChoiceField(queryset=Option.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
       self.fields['relevantoption'].label="Treatment Options"

class SelectOutcomeForOptionForm(forms.ModelForm):
    class Meta:
       model = StateOption
       exclude = ['partstate', 'partoption']

    def __init__(self, *args, **kwargs):
       disease=kwargs.pop('disease', None)
       super(SelectOutcomeForOptionForm, self).__init__(*args, **kwargs)
       self.fields['relevantoutcome']=forms.ModelMultipleChoiceField(queryset=Outcome.objects.filter(relevantdisease_id=disease),required=True, widget=forms.CheckboxSelectMultiple)
       self.fields['relevantoutcome'].label="Treatment Outcomes"

视图.py

def stateoptionoutcome(request, disease_id, state_id):

    state = get_object_or_404(State, pk=state_id)
    disease = get_object_or_404(Disease, pk=disease_id)

    if request.method == "POST":
        optionForm = SelectOptionForStateForm(request.POST, disease=disease, instance=state)
        outcomeForm = SelectOutcomeForOptionForm(request.POST, disease=disease, instance=state)

        if optionForm.is_valid() and outcomeForm.is_valid(): 
           #Deletes state objects so there are no duplicate options in the database
           try:
               state_option = StateOption.objects.filter(partstate=state).delete()

           except StateOption.DoesNotExist:
               state_option = None

           #Saves user options to database
           for option_id in request.POST.getlist('relevantoption'):
               state_option = StateOption.objects.create(partstate=state, partoption_id=int(option_id))

               #Deletes stateoption objects found in StateOptionOutcome 
               try:
                   state_option_outcome = StateOptionOutcome.objects.filter(stateoption=state_option).delete()

               except StateOptionOutcome.DoesNotExist:
                   state_option_outcome = None

               #Saves user outcomes to database
               for outcome_id in request.POST.getlist('relevantoutcome'):
                   state_option_outcome = StateOptionOutcome.objects.create(stateoption=state_option, relevantoutcome_id=int(outcome_id))

           return HttpResponseRedirect(reverse('diseasestateoptionlist', kwargs={'disease_id':disease_id, 'state_id':state_id}))

模型.py

class State(models.Model):
       state = models.CharField(max_length=255)
       relevantdisease = models.ForeignKey(Disease)
       relevantoption = models.ManyToManyField(Option, through='StateOption')

class StateOption(models.Model):
       partstate = models.ForeignKey(State)
       partoption = models.ForeignKey(Option)
       relevantoutcome = models.ManyToManyField(Outcome, through='StateOptionOutcome')

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

1 回答 1

0

我能够使用这个解决#2:

stateoptionlist = StateOption.objects.filter(partstate_id=state_id) 
if not stateoptionlist:
    stateoption = state 
else: 
    stateoption = stateoptionlist[0]

如果返回一个空列表(即表中没有记录),我将传递该state实例。更新 views.py,对于每个,我的实例都被替换为.stateoptionlistStateOptionSelectOutcomeForOptionFormstateoption

我很想看看是否有更有效的方法来解决#2。

于 2013-09-18T23:10:23.293 回答