sammy88888888
sammy88888888

Reputation: 478

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

Upvotes: 2

Views: 166

Answers (1)

mipadi
mipadi

Reputation: 410562

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(...)

Upvotes: 4

Related Questions