简体   繁体   English

多对多保存django

[英]Many to many save django

I am creating a news application where there is a many-to-many relationship between articles and authors. 我正在创建一个新闻应用程序,其中文章和作者之间存在多对多关系。 The models I currently have look like this: 我目前拥有的模型如下所示:

class Author(models.Model):
    name = models.CharField(max_length=100, null=True)

class Article(models.Model):
    authors = models.ManyToManyField(Author)
    article_title = models.CharField(max_length=250, unique_for_date="pub_date", null=True)
    pub_date = models.DateTimeField(null=True)

The data structure I have looks like this: 我的数据结构如下所示:

{'contributors': [{'author': 'Author One'}, {'author': 'Author Two'}],
 'publication_date': '2016-01-20T19:58:20Z',
 'title': 'Article title'}

I am trying to insert the data preserving the relationship between articles and authors but cannot figure out how to insert multiple authors in one go. 我试图插入保留文章和作者之间关系的数据,但无法弄清楚如何一次性插入多个作者。 The code I currently have looks like this but throws an AttributeError: 'tuple' object has no attribute 'authors' error: 我目前拥有的代码看起来像这样,但抛出AttributeError: 'tuple' object has no attribute 'authors'错误:

contributor = data['contributors']
publication_date = data['publication_date']
title = data['title']
a = Article.objects.get_or_create(
    article_title=title,
    pub_date=publication_date,
)
for c in contributor:
    author = c['author']
    au = Author.objects.get_or_create(name=author)
    a.authors.add(au)

Any suggestions, help, guidance much appreciated. 任何建议,帮助,指导深表感谢。 Let me know if anything needs clarifying. 让我知道是否需要澄清。 Oh, and I'm using python3.5 and Django1.9. 哦,我正在使用python3.5和Django1.9。 Cheers 干杯

UPDATE UPDATE

I hove got this working by altering the code to this: 我通过将代码更改为以下方式来完成此工作:

a = Article.objects.get_or_create(
    article_title=title,
    pub_date=publication_date,
)

for c in contributor:
    article = Article.objects.get(article_title=title)
    author = Author.objects.create(name=c['author'])
    article.authors.add(author)

However, I would like to use use get_or_create on the author but this results in the error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author' . 但是,我想在author上使用use get_or_create ,但这会导致错误: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author' Any thoughts? 有什么想法吗?

FINAL UPDATE 最后更新

Solved by changing: 通过更改解决:

author = Author.objects.create(name=c['author'])

to: 至:

author, created = Author.objects.get_or_create(name=c['author'])

as suggested by @mipadi 如@mipadi建议

get_or_create returns a 2-tuple (object, created), the second element being a boolean indicating if the object was created or not. get_or_create返回一个2元组(对象,已创建),第二个元素是一个布尔值,指示是否创建了对象。 So a is a tuple. 所以a是元组。 You should do something like this: 您应该执行以下操作:

a, created = Article.objects.get_or_create(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM