gpt4 book ai didi

python - 保存 m2m 关系的 Django 问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:16 25 4
gpt4 key购买 nike

我过去能够保存与表单的 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 的各种排列,但都没有成功 :(

有什么想法吗?

最佳答案

您正在尝试将一个客户端分配给 ManyToMany 字段。如果它是客户端的 ForeignKey,这将起作用,但对于 ManyToMany,您将必须执行如下操作:

temp.client.add(client)

注意:必须先保存temp,然后才能分配客户。这是因为 Django 使用一个表将客户端映射到文件,如果该文件最初不存在,则无法添加带有空键的行。查看 Django 生成的表结构应该有助于理清思路。

关于python - 保存 m2m 关系的 Django 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com