Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

many to many - 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'
question from:https://stackoverflow.com/questions/8095813/attributeerror-manyrelatedmanager-object-has-no-attribute-add-i-do-like-in

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...