属性错误:“ManyRelatedManager”对象没有属性“add”?我确实喜欢 django 网站,但遇到了这个错误

发布于 2024-12-14 16:12:35 字数 581 浏览 5 评论 0原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

肩上的翅膀 2024-12-21 16:12:35

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

,然后将文章添加到类别,您必须

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

注意 - 我们无法判断< code>through 字段被调用,因此 Membership 是一个猜测,受到 django 文档

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文