A
A
Anton2019-10-04 20:19:45
Django
Anton, 2019-10-04 20:19:45

How to form a context for a template from several related tables?

Models: Blog, Section, Article, Author.

class Blog(models.Model):
    name = models.CharField()

class Section(models.Model):
    name = models.CharField()
    authors = models.ManyToManyField(Author, through='Article')
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)

class Article(models.Model):
    name = models.CharField()
    section = models.ForeignKey(Section, on_delete=models.CASCADE)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

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

Desired page structure with author details:
Данные автора.
___________________________
Имя блога 1.
  Имя раздела 1.
    Имя статьи 1.
    Имя статьи 2.
  Имя раздела 2.
  ...
Имя блога 2.
  Имя раздела 1.
    Имя статьи 1.
    ...
___________________________

I can't figure out how to add the context to be passed to the template so that I can cycle through the author's blog-section-article names.
{% for blog in blogs %}
    {{ blog.name }}
    {% for section in blog.section_set.all %}
        {{ section.name }}
        {% for article in section.article_set.all %}
            {{ article.name }}

So everything is displayed in a row, and not just data on a specific author.
class DetailView(generic.DetailView):
    model = Author
    template_name = 'author_details.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        blogs = Blog.objects.filter(section__article__author=self.object)
        context['blogs'] = blogs
        return context

Can anyone suggest the correct approach?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2019-10-05
@Gambetto

The topic prompted the idea https://www.reddit.com/r/django/comments/85i7q7/ho...
Formed dictionaries in context.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question