Home > OS >  Unable to get relation attribute in Django, many-to-many relationship
Unable to get relation attribute in Django, many-to-many relationship

Time:01-01

models.py:

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ManyToManyField(Author)
   
    def __str__(self):
        return self.title

I'm able to filter books by the author relation:

>>> Book.objects.filter(author__name__contains="Fyodor")
<QuerySet [<Book: Crime and Punishment>, <Book: The Brothers Karamazov>]>

However, I'm unable to get the book's author:

>>> all_books = Book.objects.all()
>>> all_books[0].author
<django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fdf068a2b20>
>>> all_books[0].author.name
>>>

Any suggestions?

CodePudding user response:

You have a ManyToMany relation between books and authors, so each book will have many authors. Hence book.author gives you a queryset of authors.

Thus you need to do something like this:

# get a single book:
book = Book.objects.get(id=<the-book-id>)

# get all the authors of a book:
authors = book.author.all()

# get the first author of the book:
first_author = authors.first()
name = first_author.name
  • Related