我想删除外键的值。这里是我的模型:删除外键
class WatchList(models.Model):
user = models.ForeignKey(User)
class Thing(models.Model)
watchlist = models.ForeignKey(WatchList, null=True, blank=True)
我想从用户的WatchList
删除Thing
。我试图做这种方式,但这种删除整个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
如何删除从用户的WatchList
一个Thing
而不删除整个事情?
EDIT(意识到我应该使用ManyToMany
关系多亏了评论者!)
class Thing(models.Model)
watchlist = models.ManyToManyField(WatchList)
EDIT(试图删除多对多):
thing = get_object_or_404(Thing, pk=id)
wl = WatchList.objects.get(user=request.user)
if wl.user == request.user:
thing.watchlist.remove(wl)
应该'Thing'保留在数据库中,或者被完全删除? – Izkata
此外,除非给定的'Thing'只能在1个用户的监视列表中,否则您可能需要使用[ManyToMany](https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/) )字段而不是ForeignKey – Izkata
如果你确实留下了fk(这可能是错误的),你正在寻找'thing.watchlist = None'。 –