A
A
Ayaks772017-04-22 07:29:02
Django
Ayaks77, 2017-04-22 07:29:02

Outputting multiple models in one Django template?

Good day! I'm making a Django forum and I've run into a problem. There is a simple view that is responsible for the main content of the main forum page:

class SectionsListView(ListView):
    template_name = 'sections.html'
    queryset = Section.objects.all()

The problem is that it is necessary to output a lot of additional information to this template from four models at once, connected step by step by ForeignKey.
The only solution I've found is to predefine relationships in additional methods on the models themselves, something like this:
def get_category(self):
        return Category.objects.filter(section_category=self)

and sometimes like this:
def get_topic_count(self):
        topic_count = 0
        themes = Theme.objects.filter(category_theme=self)
        for theme in themes:
            topic_count += theme.get_topic().count()
        return topic_count

since it is inconvenient to make multiple nested loops in a template, and it is problematic for layout.
Something tells me that this is a wrong decision, I have to create a function for the sake of a few numbers, and this probably doesn’t really affect the performance.
Actually, the question is, how else can you display information from different models filtered by ForeignKey or some other connection into one template?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question