我在使用Django ManyToManyField时出错

我在使用Django ManyToManyField时出错,django,manytomanyfield,Django,Manytomanyfield,in 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:

in 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”的值才能使用此多对多关系。

要添加或删除创建对象所需的多个字段。
未创建对象时,无法添加或删除许多字段,因为该对象没有id且未保存在数据库中。
当对象保存在数据库中时,数据库将自动为其设置id。
因此,在您的情况下,
wc=WatchCount(user=request.user)
是在django代码中创建的,但它没有保存到数据库中,因此它没有id。

wc.save()
将对象添加到数据库中,然后您可以添加或删除许多字段。

您正在创建WatchCount对象,但没有保存它…当您创建wc=WatchCount(user=request.user)等对象时,您正在创建python对象,但没有将其插入数据库中…您需要先保存它:
we.save()

然后您可以使用删除或添加。

访问滚动一点,他们已经讨论了这一点
ValueError:“”需要为字段“id”设置一个值才能使用此多对多关系。
查看Django用户指南:可能是您创建的两个对象没有链接。