gpt4 book ai didi

django - AttributeError : 'ManyRelatedManager' object has no attribute 'add' ? 我喜欢在 django 网站上但是得到了这个错误

转载 作者:行者123 更新时间:2023-11-28 19:35:09 32 4
gpt4 key购买 nike

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 字段具有直通关系。假设您的模型至少类似于以下内容

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

注意 - 我们无法判断 through 字段的名称,因此 Membership 是一个猜测,灵感来自 django docs

关于django - AttributeError : 'ManyRelatedManager' object has no attribute 'add' ? 我喜欢在 django 网站上但是得到了这个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8095813/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com