manytomany - django models



AttributeError:'ManyRelatedManager'對像沒有屬性'add'? 我喜歡在django網站,但得到了這個錯誤 (1)

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

然後將條目添加到您必須的Category

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

注意 - 我們無法分辨through字段被調用的內容,因此Membership是一種猜測,受到django文檔的啟發

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'