Lord_JABA
Lord_JABA

Reputation: 2625

How to add model object to many to many field in django.1.9 and not get TypeError

I got:

Author(models.Model):
    name=models.CharField("name", max_length=100)
Entry(models.Model):
    (...)
    authors = models.ManyToMany(Author, blank=true)

def findAuthors(input):
    (...)
    authors = []
    for name in names:
        authors.append(Author.objects.get_or_create(name=name))
    return authors

and I'm trying to do:

e = Entry.objects.first() #for exmple
authors = findAuthors()
if authors:
    for author in authors:
        e.authors.add(author)

Why am I getting the following error?

TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'` 

Upvotes: 0

Views: 80

Answers (1)

Alasdair
Alasdair

Reputation: 308849

The get_or_create method returns a tuple, not just the object. You could fix it by changing your code to:

authors = []
for name in names:
    author, created = Author.objects.get_or_create(name=name)
    authors.append(author)
    return authors

Upvotes: 1

Related Questions