N
N
nurzhannogerbek2018-02-23 11:23:25
Django
nurzhannogerbek, 2018-02-23 11:23:25

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)

I want to display in the template all sections and products related to this section. I used Django's built-in regroup tag for this (see below), but ran into a problem. Firstly, sections that have no products are not displayed. Secondly, there are products that have NULL in the section field in the database; they also need to be grouped. What can you advise? I would be very grateful for an example.
views.py:
context['products'] = Product.objects.select_related('section').order_by('section')

template:
{% 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

1 answer(s)
N
nurzhannogerbek, 2018-02-27
@nurzhannogerbek

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 %}

For products that do not have a link to a section, you need to create a separate queryset in the view.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question