AttributeError:'ManyRelatedManager'对象没有属性'add'?我喜欢在django网站,但得到了这个错误

时间:2011-11-11 15:02:39

标签: django many-to-many models

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'

1 个答案:

答案 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

的启发