Answer the question
In order to leave comments, you need to log in
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()
Данные автора.
___________________________
Имя блога 1.
Имя раздела 1.
Имя статьи 1.
Имя статьи 2.
Имя раздела 2.
...
Имя блога 2.
Имя раздела 1.
Имя статьи 1.
...
___________________________
{% for blog in blogs %}
{{ blog.name }}
{% for section in blog.section_set.all %}
{{ section.name }}
{% for article in section.article_set.all %}
{{ article.name }}
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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question