我創建一個新聞應用程序,其中有文章和作者之間的許多一對多的關係。目前,我有這個樣子的模型:多對多保存的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
使用使用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所建議
我給一個嘗試,但現在我得到一個非常無益的錯誤:'類型錯誤:int()函數的參數必須是一個字符串,一類字節對象,數字,而不是'作者' – sammy88888888