Answer the question
In order to leave comments, you need to log in
How to make a correct list of records of related data models?
Hello, please help me figure it out!
There are two data models: Section (Section), Product (Product).
models.py:
class Section(models.Model):
name = models.CharField(max_length=255, blank=False, null=True,)
class Product(models.Model):
name = models.CharField(max_length=255, blank=False, null=True,)
section = models.ForeignKey(Section,on_delete=models.CASCADE)
context['products'] = Product.objects.select_related('section').order_by('section')
{% regroup products by section as products_by_section %}
{% for section in products_by_section %}
{{ section.grouper}}
{% for product in section.list %}
{{ product }}
{% endfor %}
{% endfor %}
Answer the question
In order to leave comments, you need to log in
Solved the problem in the following way.
# Получаем все секции
sections = Section.objects.all().prefetch_related('product_set')
# Cоздаем словарь с секциями и принадлежащим им продуктам
section_products_dict = {}
for section in sections:
section_products_dict[section.id] = section.product_set.all()
# Передаем наш словать в шаблоне
context['dictionary'] = section_products_dict
{% for section, products in dictionary.items %}
{{section}}
{% for product in products %}
{{product}}
{% endfor %}
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question