CMorgan
CMorgan

Reputation: 693

display model fieldnames in Django listview

In my listview I want to display several fields from two models containing a many-to-many field. I can display the correct values from one table, but then I cannot access the other table with the many-to-manyfield.

Models.py

class Books(models.Model):
    title = models.CharField(max_length=100)

class Author(models.Model):

    book = models.ManyToManyField(Books)
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=200)

Views.py

class BooksListView(ListView):
    context_object_name = 'booklist'
    model = Author 
    template_name = 'Books/books_list.html'

Book_list.html

{% for books in booklist %}
    <h5><li class="list-group-item list-group-item-light"">
    {{books.book.all}}:{{books.first_name}} {{books.last_name}}</li></h5>
{% endfor %}

The first and lastname are displayed properly, but the books.book.all ()i know this is the wrong query) returns a queryset containing the title (which is what I need, but this is in format <QuerySet [<Books: Book Title>]>. But books.book.title doesnt seem to work. What I want to display is "booktitle - firstname lastname", and because I am using two tables, I need a many-to-many relationship. Any thoughts?

Upvotes: 0

Views: 606

Answers (1)

Anonymous
Anonymous

Reputation: 12090

The many-to-many relationship goes both ways, so you don't need to base everything around authors.

class BooksListView(ListView):
    context_object_name = 'booklist'
    model = Book 
    template_name = 'Books/books_list.html'

And the template:

{% for books in booklist %}
    <li class="list-group-item list-group-item-light">
        <h5>{{ book.title }}</h5>
        <p>
        {% for author in book.author_set.all %}
        {{ author.first_name }} {{ author.last_name }}{% if not forloop.last %}, {% endif %}
        {% endfor %}
        </p>
    </li>
{% endfor %}

Notes:

  • By default, the related_name is {{ModelName}}_set (author_set in this case). If you want something more natural you can set related_name='authors'.
  • There will be a query made to the databse for every book in the list and this can be quite slow with a lot of data, so take a look at prefetch_related().

Upvotes: 1

Related Questions