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'
答案 0 :(得分:63)
JamesO是正确的 - 看起来你的Category.articles字段有一个完整的关系。假设您的模型至少类似以下
class Article(models.Model):
name = models.CharField(max_length=128)
class Category(models.Model):
name = models.CharField(max_length=128)
articles = models.ManyToManyField(Article, through='Membership')
class Membership(models.Model):
article = models.ForeignKey(Article)
category = models.ForeignKey(Category)
author = models.CharField()
然后将Article
添加到Category
,您必须
m = Membership(article=article, category=category, author="Dan TM")
m.save()
注意 - 我们无法确定调用through
字段的内容,因此Membership
是一种猜测,受到django docs