Django:禁止直接分配给多对多集的前端。使用user.set()代替 [英] Django : Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead

查看:449
本文介绍了Django:禁止直接分配给多对多集的前端。使用user.set()代替的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将当前登录的用户添加为 ManyToManyField 的另一个关系时,出现此错误。

I am getting this error when I try to add the current logged in user into another relation as ManyToManyField.

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead.

这是我的代码:

Views.py

def add_to_cart(request , item):
    name = item
    size = request.POST.get("size")
    extras = request.POST.get("extras")
    c = Cart(item=name , size=size , extras=extras , user=request.user)
    c.save()
    return render(request , "orders/add_items.html" , {"message":f"{name} added to cart"})

Models.py

class Cart(models.Model):
    item = models.CharField(max_length=64)
    size = models.DecimalField(max_digits=5,decimal_places=2)
    extras = models.CharField(max_length=64 , null=True, blank=True)
    user = models.ManyToManyField(User , related_name="member")

def __str__(self):
    return f"{item} added by {user}"


推荐答案

您需要先保存购物车,然后才能进行广告d个项目到多对多字段。

You need to save the cart before you can add items to the many-to-many field.

c = Cart(item=name , size=size , extras=extras)
c.save()
c.user.add(request.user)

保存后,您还可以使用 set()。请注意,这将删除集合中未指定的所有相关用户(尽管在这种情况下,这是一个新列表,因此没有任何用户)。

You could also use set() after saving. Note this will remove any related users not specified in the set (although in this case it's a new list so there aren't any).

c.user.set([request.user]

最后,确定要吗?一个多对多字段吗?这允许购物车属于多个用户。如果是这样,我将字段命名为 users ,而不是 user 。如果每个购物车只需要一个 user ,那么我将使用 ForeignKey 代替。您的related_name 成员也没有意义,这用于获取与用户相关的购物车,所以我希望您使用 carts

Finally, are you sure you want a many-to-many field for this? That allows a cart to belong to multiple users. If that's the case, I would name the field users, not user. If you only want one user per cart, then I would use a ForeignKey instead. Your related_name members doesn't make sense either. This is used to get the carts related to a user, so I would expect you to use carts instead.

这篇关于Django:禁止直接分配给多对多集的前端。使用user.set()代替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆