5

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

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'

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

4

2 回答 2

4

z.watchlist是参考本身,它不是关系经理。只需分配:

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

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

于 2013-10-21T17:33:55.280 回答
2

As karthikr said you may be getting confused with manytomanyfield, if you really want an intermediary model, you might have something like this:

# 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
...

Otherwise you might want to extend the user model.

于 2013-10-21T18:03:58.023 回答