How to get many to many value in Django template

Viewed 29

I have 2 app: authors_app and books_app

authors_app.models:

class Author(models.Model):
    name = models.CharField(max_length=250, unique=True)

books_app.models:

class Book(models.Model):
    author = models.ManyToManyField(Author, related_name='authors')

Authors_app Views.py

class AuthorBio(DetailView):
    model = Author
    template_name = 'author-bio.html'

Problem

I need to get all the book published by the author. In my template I try:

{% for book in author.books.all %}
...
{% endfor %}

But this doesn't work

Question

How can I get all the books by the author

1 Answers

First change

author = models.ManyToManyField(...)

to

authors = models.ManyToManyField('authors_app.author', related_name="books") 

now you can access books using related_name: author.books.all()

Code Example:

>>> from authors_app.models import Author
>>> Author.objects.create(name="J.K. Rowling")
<Author: J.K. Rowling>
>>> from books_app.models import Book
>>> jk = Author.objects.first()
>>> jk
<Author: J.K. Rowling>
>>> Book.objects.create(name="Harry Potter: Chamber of secrets")
<Book: Harry Potter: Chamber of secrets>
>>> hp = Book.objects.first()
>>> hp.authors.set([jk])
>>> jk.books.all()
<QuerySet [<Book: Harry Potter: Chamber of secrets>]>
>>> 

Pay attention to your queryset performance.

Related