在“父表”中,我有很多对象。用户具有一种可以选择父对象之一的表单。看起来像这样:
class ChildForm(forms.ModelForm):
class Meta:
model = OrderingMassage
fields = ('parent',
'name')
现在,我想为用户在Parent表中选择的每个对象“ parent”将“ on_off button”值更改为False。 我该如何恢复?我可以使用什么?我可以使用一种表格来查看吗?
例如:
models.py
class Parent(models.Model):
name = models.CharField(max_length=15)
on_off_button = models.BooleanField(deflaut=True)
class Child(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
name = models.CharField(max_length=15)
views.py
if request.method == 'POST' and 'child_btn' in request.POST:
child_form = ChildForm(request.POST)
if child_form.is_valid():
child = child_form.save(commit=False)
name = child_form.cleaned_data['name']
parent = child_form.cleaned_data['parent']
# Can I add an element here that will change the value parent.id on False
child.name = name
child.parent = parent
child.save()
else:
child_form = ChildForm()
任何帮助将不胜感激。
答案 0 :(得分:1)
在您看来,您可以执行以下操作:
if request.method == 'POST' and 'child_btn' in request.POST:
child_form = ChildForm(request.POST)
if child_form.is_valid():
child = child_form.save(commit=False)
name = child_form.cleaned_data['name']
parent = child_form.cleaned_data['parent']
child.name = name
child.parent = parent
child.save()
#get the parent object related to the parent selected by the user
parent = Parent.objects.get(id=parent.id)
parent.on_off_button = False
parent.save()
#or can you try this method to check
parent.on_off_button=False
parent.save()
else:
child_form = ChildForm()