Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'ManyRelatedManager' object has no attribute 'add'? I do like in django website but got this error

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' 
like image 777
Totty.js Avatar asked Nov 11 '11 15:11

Totty.js


1 Answers

JamesO is correct - it looks like your Category.articles field has a through relationship. Assuming that your models at least resemble the following

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() 

then to add an Article to a Category you must

m = Membership(article=article, category=category, author="Dan TM") m.save() 

Note - we can't tell what the through field is called, so Membership is a guess, inspired by the django docs

like image 146
danodonovan Avatar answered Sep 17 '22 22:09

danodonovan