我想删除 ForeignKey 的值。这是我的模型:
class WatchList(models.Model):
user = models.ForeignKey(User)
class Thing(models.Model)
watchlist = models.ForeignKey(WatchList, null=True, blank=True)
我想Thing
从用户的WatchList
. 我试图这样做,但这会删除整个Thing
,而不是它在监视列表中的位置:
def delete(request, id):
thing = get_object_or_404(Thing, pk=id)
if thing.watchlist.user == request.user:
thing.watchlist.delete() ## also tried thing.watchlist.user.delete() unsuccessfully
return HttpResponseRedirect('somewhere')
else:
# other stuff
如何在不删除整个内容Thing
的情况下从用户中删除?WatchList
编辑(意识到我应该使用ManyToMany
关系。感谢评论者!)
class Thing(models.Model)
watchlist = models.ManyToManyField(WatchList)
编辑(试图删除多对多):
thing = get_object_or_404(Thing, pk=id)
wl = WatchList.objects.get(user=request.user)
if wl.user == request.user:
thing.watchlist.remove(wl)