AttributeError:'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' 

JamesO是正确的 – 它看起来像你的Category.articles领域有一个贯穿的关系。 假设你的模型至less类似于以下内容

 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文档的启发