简体   繁体   中英

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

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

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