2013-10-24 166 views
1

我想删除外键的值。这里是我的模型:删除外键

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) 
+0

应该'Thing'保留在数据库中,或者被完全删除? – Izkata

+1

此外,除非给定的'Thing'只能在1个用户的监视列表中,否则您可能需要使用[ManyToMany](https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/) )字段而不是ForeignKey – Izkata

+0

如果你确实留下了fk(这可能是错误的),你正在寻找'thing.watchlist = None'。 –

回答

2

第一(好的,你已经在你的编辑中注意到了),你有一个多对多的关系。

Whand you cheanges this,你可以设置从Thing.watchlist表删除用户条目。你会在the django documentation here中找到很多关于如何使用这些例子的例子。

总之:你可以做my_thing.watchlist.remove(object_to_be_removed)

...并回答你原来的问题(强制万一有人运行到这个问题:就在ForeignKey的属性设置为Nonemy_thing.watchlist = None

+0

感谢您的回答@OBu。我认为我更接近答案,就像上面编辑中发布的那样,但我仍然无法删除WatchList。任何想法我做错了什么?感谢您的想法! –

+0

是否有任何错误?你执行了你的代码之后,你检查了你的数据库并且发现了任何改变吗你确定,if语句之后的代码是否被实际执行? (例如通过在if之后或通过写入日志消息来设置断点) – OBu