我在m2m模型中创建关系时遇到问题。
models.py
class ECG(models.Model):
procedure= models.ManyToManyField('Procedure')
...
class Procedure(models.Model):
basic_info= models.IntegerField(default=0)
views.py
def newECG(request, procedure_id):
if request.method == 'POST':
form = NewECG(request.POST)
if form.is_valid():
form.save()
info = IncomingProcedure.objects.get(id=procedure_id)
form.procedure.add(info) #HERE IS A PROBLEM
return HttpResponseRedirect('/system/')
else:
form = NewECG()
return render(request, 'system/ecg.html', {'form': form})
forms.py
class NewECG(ModelForm):
class Meta:
model = ECG
exclude = ['procedure']
# fields = '__all__'
fields = [ ... ] # rest fields, except procedure
Procedure
已经存在。我需要创建与过程相关的newECG
。心电图表格在db中保存。问题是当我想使用add()
函数时。
ERROR :'NewECG' object has no attribute 'procedure', exception location: views.py
答案 0 :(得分:1)
ModelForm
实例没有在模型上定义的procedure
属性。但是,ECG
模型实例由表单的save(...)
方法返回,确实有它:
ecg_instance = form.save()
info = IncomingProcedure.objects.get(id=procedure_id)
# info = Procedure.objects.get(id=procedure_id)
ecg_instance.procedure.add(info)
答案 1 :(得分:0)
你忘记了一步:
def newECG(request, procedure_id):
if request.method == 'POST':
form = NewECG(request.POST)
if form.is_valid():
ecg = form.save()
info = IncomingProcedure.objects.get(id=procedure_id)
ecg.procedure.add(info) #HERE IS A PROBLEM
return HttpResponseRedirect('/system/')
答案 2 :(得分:0)
我无法理解你为什么要在{strong> views.py
中向IncomingProcedure.objects
添加from
如果要将其保存在数据库中,只需执行以下操作:
<强> views.py 强>
# ... Your codes:
M = form.save() # save your class instance to M variable
info = IncomingProcedure.objects.get(id=procedure_id)
M.procedure.add(info) # save procedure instance to your object(An ECG model instance)