【发布时间】:2011-12-27 02:30:54
【问题描述】:
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'
【问题讨论】:
-
您使用的是直通模型吗?如果是这样,.add 和 .create 将不起作用。
-
使用
category.articles.set(category.articles.all() | article)适用于我的场景。
标签: django many-to-many models