属性错误:“ManyRelatedManager”对象没有属性“add”?我确实喜欢 django 网站,但遇到了这个错误
for item in data:
category_id = item['category_id']
del item['category_id']
category = Category.objects.get(pk=category_id)
code = item['code']
try:
article = Article.objects.get(pk=code)
except:
article = Article(**item)
article.save()
# at this point I have the article & category, but the next
# statement throws me an error:
category.articles.add(article)
category.save()
错误是:
AttributeError: 'ManyRelatedManager' object has no attribute 'add'
for item in data:
category_id = item['category_id']
del item['category_id']
category = Category.objects.get(pk=category_id)
code = item['code']
try:
article = Article.objects.get(pk=code)
except:
article = Article(**item)
article.save()
# at this point I have the article & category, but the next
# statement throws me an error:
category.articles.add(article)
category.save()
The error is:
AttributeError: 'ManyRelatedManager' object has no attribute 'add'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JamesO 是正确的 - 看起来您的 Category.articles 字段具有直通关系。假设您的模型至少类似于以下内容
,然后将
文章
添加到类别
,您必须注意 - 我们无法判断< code>through 字段被调用,因此
Membership
是一个猜测,受到 django 文档JamesO is correct - it looks like your Category.articles field has a through relationship. Assuming that your models at least resemble the following
then to add an
Article
to aCategory
you mustNote - we can't tell what the
through
field is called, soMembership
is a guess, inspired by the django docs