处理数据库记录更新和创建的正确方法 - object.filter更新

时间:2013-09-19 01:11:09

标签: django django-forms

我正在尝试管理数据库中的记录,以便用户能够更新数据库中的记录。目前,我的实现检查以查看StateOption表中是否存在记录。如果是,则实例为stateoption。如果记录不存在,则实例为state。表单验证后,根据实例,它将创建新记录或更新现有记录。更新记录时,我收到此错误:

Cannot assign "1": "StateOptionOutcome.stateoption" must be a "StateOption" instance.

我知道我需要StateOption实例,但我的表单使用State实例,因此我不确定如何解决此问题。有什么想法吗?

views.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)

    #instansiate treatment outcomes
    stateoptionlist = StateOption.objects.filter(partstate_id=state_id) 
    if not stateoptionlist:
        stateoption = state #pass the state instance if there is no record of outcomes
    else: 
        stateoption = stateoptionlist[0]

    if request.method == "POST":
        optionForm = SelectOptionForStateForm(request.POST, disease=disease, instance=stateoption)


        if optionForm.is_valid(): 

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

models.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)

0 个答案:

没有答案