过去我能够与表格保存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
的各种排列,但没有取得多大成功:(
有什么想法吗?
答案 0 :(得分:3)
您正尝试将一个客户端分配给ManyToMany字段。如果它是客户端的ForeignKey,这将有效,但对于ManyToMany,您将必须执行以下操作:
temp.client.add(client)
注意:在分配客户端之前,必须先保存temp
。这是因为有一个表Django使用映射客户端到文件,如果文件不存在,则不能添加具有空键的行。查看Django生成的表结构应该有助于清理。
答案 1 :(得分:2)
您正在尝试在保存对象之前保存m2m关系(commit = False)。要创建客户端和文件之间的关系,需要先保存文件。
见这里: Django: instance needs to have a primary key value before a many-to-many relationship