Django向ForeignKey添加值

时间:2013-10-21 17:17:32

标签: python django views models

我正在尝试为用户设置“观看”某些项目的方式(即将项目添加到包含其他用户的其他项目的列表中):

class WatchList(models.Model):
    user = models.ForeignKey(User)

class Thing(models.Model):
    watchlist = models.ForeignKey(WatchList, null=True, blank=True)

如何向用户Thing添加WatchList

>>> from myapp.models import Thing
>>> z = get_object_or_404(Thing, pk=1)
>>> a = z.watchlist.add(user="SomeUser")

  AttributeError: 'NoneType' object has no attribute 'add'

如何将项目添加到关注列表?和/或这是设置我的模型字段的适当方法吗?谢谢你的任何想法!

2 个答案:

答案 0 :(得分:4)

z.watchlist是引用本身,它不是关系管理器。只需指定:

z.watchlist = WatchList.objects.get(user__name='SomeUser')

请注意,这假设每个用户只有一个WatchList

答案 1 :(得分:0)

正如karthikr所说,你可能会对manytomanyfield感到困惑,如果你真的想要一个中间模型,你可能会有这样的事情:

# Models:
class WatchList(models.Model):
    user = models.ForeignKey(User, related_name='watchlists')

class Thing(models.Model):
    watchlist = models.ForeignKey(WatchList, null=True, blank=True)

# Usage:
user = User.objects.get(name='???') # or obtain the user however you like
wl = WatchList.objects.create(user=user)
thing = Thing.objects.get(id=1) # or whatever
thing.watchlist = wl
thing.save()

# get users watch lists:
user.watchlists
...

否则您可能需要extend the user model