我正在尝试使用 m2m 结构保存多选复选框表单,但我的值没有保存到数据库中。
我有一个状态和选项。一个状态可以有多个选项,选项可以有多个状态。在实践中,我想为每个状态保存多个选项,然后将连接保存在中间 StateOption 表中。没有产生错误,但是当我检查我的数据库时,什么都没有保存。
此外,如果您发现我设置数据库结构的方式有任何问题,请随时发表评论。我是数据库和 django 的新手。
模型.py
class Option(models.Model):
relevantdisease = models.ForeignKey(Disease)
option = models.CharField(max_length=255)
class State(models.Model):
state = models.CharField(max_length=255)
relevantdisease = models.ForeignKey(Disease)
relevantoption = models.ManyToManyField(Option, blank=True, through='StateOption')
#intermediate table may not be needed
class StateOption(models.Model):
state_table = models.ForeignKey(State)
option_table = models.ForeignKey(Option)
表格.py
class StateOptionForm(forms.ModelForm):
option_choices = forms.ModelMultipleChoiceField(queryset=Option.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
class Meta:
model = State #StateOption if I use the intermediate table
exclude = ['state_table', 'option_table']
视图.py
def stateoption(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":
form = StateOptionForm(request.POST, instance=state)
if form.is_valid():
profile = form.save(commit=False)
profile.user = request.user
profile.save() #this and the line below is probably where the problem is
form.save_m2m()
#stateoption = StateOption.objects.create(state_table=state, option_table=profile) <--produces an error saying that the instance needs to be Option
return HttpResponseRedirect(reverse('success'))
else:
form = StateOptionForm(instance=state)
context = {'state': state, 'disease':disease, 'option': form }
return render(request, "stateoption.html", context)
更新 此用例可能不需要中间表,但随着我为这个问题增加更多复杂性,将需要它。有没有办法用中间表将此表单保存到数据库中?