我正在尝试管理数据库中的记录,以便用户能够更新数据库中的记录。目前,我的实现检查以查看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)