使用 Django ManyToManyField 时出现错误

问题描述

在view.py中

def watchlist(request,item_id):
    list=get_object_or_404(Listing,id=item_id)
    wc=WatchCount(user=request.user)
    if WatchCount.objects.filter(user=request.user,listing=list).exists():
        wc.listing.remove(list)
    else:
        wc.listing.add(list)     
    return HttpResponseRedirect(wc.get_absolute_url())

在models.py中

class WatchCount(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
    listing =  models.ManyToManyField(Listing,blank=True,related_name="watchcount")
    def __str__(self):
        return f"{self.user.username}"
    def count(self):
        return self.listing.count()
    def get_absolute_url(self):
        return reverse('list',kwargs={'item_id': self.pk})

错误

"" 需要有字段“id”的值才能使用这种多对多关系。

解决方法

在添加或删除多对多字段之前,您需要创建对象。
如果您尚未创建对象,则无法添加或删除 ManyToMany 字段,因为它没有 id 且未保存在数据库中。
当一个对象保存在数据库中时,数据库会自动为它设置一个 id。
所以在你的例子中,wc=WatchCount(user=request.user) 是在你的 Django 代码中创建的,但它没有保存到数据库中,所以它没有 id。
wc.save() 会将对象添加到数据库,然后您可以添加或删除多对多字段。

,

你正在创建 WatchCount 对象,但你没有保存它...当你创建像 wc=WatchCount(user=request.user) 这样的对象时,你正在创建 python 对象但没有将它插入数据库......你需要保存它第一的 : we.save() 然后你可以使用删除或添加。