V
V
Volton2017-04-19 03:51:44
Django
Volton, 2017-04-19 03:51:44

How to display a list of categories and related products on one page?

There are two categories:

class Category(models.Model):
    name = models.CharField(_('Название категории'), max_length=64)
    ...

class Book(models.Model):
    title = models.CharField(_('Название книги'), max_length=256)
    category = models.ForeignKey(Category, related_name='category_book')
    ...

How to make one request in a ListView to display a list of categories and related books in a template. For example:
Fiction:
- book 1
- book 2
History:
- book 3
- book 4
- book 5
, etc.
Please help, I can't do it for the second day

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexandrBirukov, 2017-04-19
@AlexandrBirukov

{% for category in categorys %}
{{ category }}
{% for book in category.category_book.all %}
{{ book }}
{% endfor %}
{% endfor %}
This is in the template, but in the view:
model = Category
context_object_name = 'categories'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question