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()
L'erreur est:
AttributeError: 'ManyRelatedManager' object has no attribute 'add'
JamesO est correct - il semble que votre champ Category.articles ait une relation directe. En supposant que vos modèles au moins ressemblent à ce qui suit
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()
puis pour ajouter un Article
à un Category
vous devez
m = Membership(article=article, category=category, author="Dan TM")
m.save()
Remarque - nous ne pouvons pas dire comment le champ through
est appelé, donc Membership
est une supposition, inspirée des Django docs