Django 保存 m2m 关系时出现问题

发布于 2024-12-08 13:04:51 字数 1980 浏览 1 评论 0原文

我过去能够保存与表单的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

行至春深 2024-12-15 13:04:51

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

temp.client.add(client)

注意:在分配客户端之前,必须先保存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:

temp.client.add(client)

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.

断桥再见 2024-12-15 13:04:51

您试图在保存对象本身之前保存 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文