U
U
user-agent2021-03-25 00:34:46
Django
user-agent, 2021-03-25 00:34:46

How to group elements by field value in Django?

There is a product model that has a ForeignKey relationship with a product group model and with a catalog model.

class Product(models.Model):
  catalog = models.ForeignKey(Catalog, related_name='catalog', on_delete=models.CASCADE)
  division = models.ForeignKey(Division, related_name='division', null=True, on_delete=models.CASCADE) #группы товаров

  title = models.CharField(max_length=500, blank=True, verbose_name='Заголовок')
        ...


When I go to the catalog section, I get products from this catalog. After I want to break these products into groups depending on the division field.

-- (catalog) Electronics
---- -- (division) Phones
------- -- (Product) apple; -- (Product) xiaomi ...

---- -- (division) Refrigerators
------- -- ...

In this case, division is not included in the catalog, but is simply displayed as the name of a group of products defined in this directory. That is, -- (division) Phones may appear in a different catalog and with other products: instead of -- (Product) apple; will be -- (Product) samsung;

How to divide elements into groups of the division field?

I tried to select division through values_list, and then scatter it over the dictionary through a cycle. It seems to work, but I would like to find a more correct solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-03-25
@user-agent

https://docs.djangoproject.com/en/3.1/ref/template...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question