简体   繁体   中英

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:

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. Cheers

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' . 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

get_or_create returns a 2-tuple (object, created), the second element being a boolean indicating if the object was created or not. So a is a tuple. You should do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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