【问题标题】:Django Adding Values to ForeignKeyDjango 将值添加到 ForeignKey
【发布时间】:2013-10-30 07:34:17
【问题描述】:

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

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'

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

【问题讨论】:

  • 我认为您对多线程感到困惑。你会做=
  • 为什么不直接与用户相关?还是您想为每个用户创建多个关注列表?
  • 如果最终我试图查询以获取特定User 正在监视的所有Things,我应该以不同的方式设置我的模型吗?将ForeignKey 从WatchList 放置到Thing,而不是我上面描述的方式会更好吗?最终目标是查询以查找特定用户正在观看的所有内容...

标签: python django views models


【解决方案1】:

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

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

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

【讨论】:

  • 好的,感谢您的意见,但我仍然很困惑。也许我的模型设置错误。如果我希望能够查询到所有Things UserWatching,,我应该使用ManyToMany 关系吗?我还希望能够获得所有UsersWatching 某个Thing.. 抱歉我的困惑,但我很欣赏你的想法!
  • 你的用户对象有一个.watchlist_set经理; user.watchlist_set.get().thing_set.all() 将是用户正在观看的所有内容。
  • 好吧,我现在超级困惑。尝试z.watchlist = WatchList.objects.filter(user__username='SomeDude') 导致ValueError: Cannot assign "[<WatchList: WatchList object>, <WatchList: WatchList object>, <WatchList: WatchList object>, <WatchList: WatchList object>]": "Thing.watchlist" must be a "WatchList" instance.
  • @NickB:这是WatchList 对象的列表,您的用户有多个。只得到 一个WatchList.objects.filter(user__username='SomeDude')[0] 将是第一个匹配的监视列表。
  • 好吧,在这种情况下,我认为我设置模型的方式可能有问题。我希望实现的是查询:Thing.objects.filter(watchlist__user__username='SomeDude'),以便我可以获得用户正在观看的所有内容。在这种情况下,我是否错误地设置了我的模型?对不起,我的困惑..
【解决方案2】:

正如 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

【讨论】:

  • 嗯好吧,这更有意义。然后我将如何查询以查找用户正在观看的所有项目?
  • 我的答案中添加了解释。
  • 好吧,这是有道理的,但我收到了AttributeError: 'User' object has no attribute 'watchlist'。任何想法为什么?
  • 相关名称是 'watchlists' 而不是 'watchlist'
  • 我将确切的代码放入我的 python 解释器中。使用上面定义的模型,此代码:>>> user.watchlists 导致AttributeError: 'User' object has no attribute 'watchlists'user.watchlist 也是如此。我错过了什么?感谢您的任何想法!
猜你喜欢
  • 1970-01-01
  • 2022-11-12
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 2017-12-16
  • 2015-02-21
相关资源
最近更新 更多