Django 保存 m2m 关系时出现问题
我过去能够保存与表单的 m2m 关系,但我目前遇到以下问题,我无法理解为什么:
# models.py
class File(models.Model):
client = models.ManyToManyField(Client)
product = models.ForeignKey(Product, related_name='item_product')
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
# forms.py
class FileForm(ModelForm):
class Meta:
model = File
exclude = ('client')
def CustomSave(self,product,client,user):
temp = self.save(commit=False)
temp.product = product
temp.client = client # < ?!?!
temp.created_by = user
temp.save()
temp.save_m2m()
return temp
# views.py
def new_client_view(request):
if request.method == 'POST':
try:
i_product = int(request.POST['product'])
except ValueError:
raise Http404()
# get a 'product' from the POST data
p = Product.objects.get(id=i_product)
formFile = FileForm(p, request.POST, auto_id='f_%s')
formItemData = ItemDataForm(p, request.POST, auto_id='i_%s')
if formFile.is_valid() and formItemData.is_valid():
c = Client()
c.save()
tempFile = formFile.CustomSave(p,c,request.user)
tempItem = ItemForm().CustomSave(tempFile,request.user)
formItemData.CustomSave(tempItem,request.user)
return redirect(client_view, c.id)
else:
return render_to_response('newClient.html', {'error':'The form was not valid'}, context_instance=RequestContext(request))
else:
return render_to_response('newClient.html', {}, context_instance=RequestContext(request))
当我尝试上述操作时,我得到:
'File' instance needs to have a primary key value before a many-to-many relationship can be used.
django 指示错误来自 temp .client = client
我尝试了 CustomSave
的各种排列,但没有取得太大成功:(
有什么想法吗?
I have been able to save m2m relationships with forms in the past, but I am currently have problems with the following and I can't understand why:
# models.py
class File(models.Model):
client = models.ManyToManyField(Client)
product = models.ForeignKey(Product, related_name='item_product')
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
# forms.py
class FileForm(ModelForm):
class Meta:
model = File
exclude = ('client')
def CustomSave(self,product,client,user):
temp = self.save(commit=False)
temp.product = product
temp.client = client # < ?!?!
temp.created_by = user
temp.save()
temp.save_m2m()
return temp
# views.py
def new_client_view(request):
if request.method == 'POST':
try:
i_product = int(request.POST['product'])
except ValueError:
raise Http404()
# get a 'product' from the POST data
p = Product.objects.get(id=i_product)
formFile = FileForm(p, request.POST, auto_id='f_%s')
formItemData = ItemDataForm(p, request.POST, auto_id='i_%s')
if formFile.is_valid() and formItemData.is_valid():
c = Client()
c.save()
tempFile = formFile.CustomSave(p,c,request.user)
tempItem = ItemForm().CustomSave(tempFile,request.user)
formItemData.CustomSave(tempItem,request.user)
return redirect(client_view, c.id)
else:
return render_to_response('newClient.html', {'error':'The form was not valid'}, context_instance=RequestContext(request))
else:
return render_to_response('newClient.html', {}, context_instance=RequestContext(request))
When I try the above I get:
'File' instance needs to have a primary key value before a many-to-many relationship can be used.
And django indicates the error comes from temp.client = client
I have tried various permutations of the CustomSave
without much success :(
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试将一个客户端分配给 ManyToMany 字段。如果它是客户端的外键,则这将起作用,但对于多对多,您必须执行以下操作:
注意:在分配客户端之前,必须先保存
temp
。这是因为 Django 使用一个表将客户端映射到文件,如果该文件首先不存在,则无法添加带有空键的行。查看 Django 生成的表结构应该有助于弄清楚事情。You're trying to assign one client to a ManyToMany field. This would work if it was a ForeignKey to a Client, but for ManyToMany, you will have to do something like:
Note:
temp
will have to be saved first, before you can assign clients. This is because there's a table Django uses mapping clients to files, and if the file doesn't first exist, you can't add a row w/ a null key. Looking at the table structure Django generates should help clear things up.您试图在保存对象本身之前保存 m2m 关系 (commit=False)。要创建客户端和文件之间的关系,需要先保存文件。
参见这里:
Django:实例在建立多对多关系之前需要有主键值
You are trying to save the m2m relationship before the object itself has been saved (commit=False). To create the relationship between the client and the file, the file needs to be saved first.
See here:
Django: instance needs to have a primary key value before a many-to-many relationship