[英]Django relationship in manyToMany models, object has no attribute
I have a problem with creating relationship in m2m models. 我在M2M模型中建立关系时遇到问题。
models.py models.py
class ECG(models.Model):
procedure= models.ManyToManyField('Procedure')
...
class Procedure(models.Model):
basic_info= models.IntegerField(default=0)
views.py 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
already exists. Procedure
已存在。 I need to create newECG
in relation with procedure. 我需要创建与过程相关的
newECG
。 ECG form is saving in db. 心电图表格保存在数据库中。 Problem is when i want to use
add()
function. 问题是当我想使用
add()
函数时。
ERROR :'NewECG' object has no attribute 'procedure', exception location: views.py
The ModelForm
instance does not have the procedure
attribute that is defined on the model. ModelForm
实例不具有在模型上定义的procedure
属性。 The ECG
model instance, however, which is returned by the form's save(...)
method, does have it: 但是,由表单的
save(...)
方法返回的ECG
模型实例确实具有它:
ecg_instance = form.save()
info = IncomingProcedure.objects.get(id=procedure_id)
# info = Procedure.objects.get(id=procedure_id)
ecg_instance.procedure.add(info)
You just forgot a step: 您只是忘记了一步:
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/')
I can't understand why you are trying to add IncomingProcedure.objects
to your from
in views.py 我不明白为什么你尝试添加
IncomingProcedure.objects
您from
在views.py
If you want save it on your database, Should simply do this: 如果要将其保存在数据库中,只需执行以下操作:
views.py 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.