簡體   English   中英

多對多保存django

[英]Many to many save django

我正在創建一個新聞應用程序,其中文章和作者之間存在多對多關系。 我目前擁有的模型如下所示:

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)

我的數據結構如下所示:

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

我試圖插入保留文章和作者之間關系的數據,但無法弄清楚如何一次性插入多個作者。 我目前擁有的代碼看起來像這樣,但拋出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)

任何建議,幫助,指導深表感謝。 讓我知道是否需要澄清。 哦,我正在使用python3.5和Django1.9。 干杯

UPDATE

我通過將代碼更改為以下方式來完成此工作:

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)

但是,我想在author上使用use get_or_create ,但這會導致錯誤: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author' 有什么想法嗎?

最后更新

通過更改解決:

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

至:

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

如@mipadi建議

get_or_create返回一個2元組(對象,已創建),第二個元素是一個布爾值,指示是否創建了對象。 所以a是元組。 您應該執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM