【发布时间】:2013-08-21 20:14:19
【问题描述】:
我正在尝试使用 m2m 结构保存多选复选框表单,但我的值没有保存到数据库中。
我有一个状态和选项。一个状态可以有多个选项,选项可以有多个状态。在实践中,我想为每个状态保存多个选项,然后将连接保存在中间 StateOption 表中。没有产生错误,但是当我检查我的数据库时,什么都没有保存。
另外,如果您发现我设置数据库结构的方式有任何问题,请随时发表评论。我是数据库和 django 的新手。
models.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)
forms.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']
views.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)
更新 这个用例可能不需要中间表,但随着我为这个问题增加更多的复杂性,它将需要它。有没有办法通过中间表将此表单保存到数据库中?
【问题讨论】:
-
好吧,不需要那个 StateOption 模型。除非我遗漏了什么,否则 ORM 应该为您创建连接表。
-
你是对的。如果我摆脱 StateOption 并在我的 StateOptionForm 中使用 model = State,表单仍然不会保存在为我创建的表 ORM 中。我只创建了一个中间表,以便它减少从 2 到 1 创建的新表。关于它为什么不保存的任何想法?
-
编辑上面的代码,去掉 StateOption 模型,然后我们来看看。
-
完成。编辑在上面
-
所以它看起来像是我的 forms.py 中的排除参数。我必须使用“相关选项”,否则这些值不会被保存。但是没有理由使用我的表格,因为“相关疾病”将是一个多选。有什么办法让我仍然可以使用我的表单?