Grouping values in Django

Asked

Viewed 119 times

1

I’m having a little trouble grouping some information from separate models.

For example: I have 3 models, a call Category, another call Group and another call Tools.

These tables will get the name and Slug of existing categories, existing groups and existing tools.

There is also a fourth model called Final. There I will have the values of various combinations between categories, groups and tools.

I would like to organize the information thus:

  • Name of Group 1

    • Tool Name 1

      • Category 1
      • Category 2
      • Category 3
    • Tool Name 2

      • Category 4
      • Category 5
      • Category 6
  • Name of Group 2

    • Tool Name 3

      • Category 7
      • Category 8
    • Tool Name 4

      • Category 9

Models

  • Group (contains the name and name of a group)
  • Tools (contains name and tools Slug)
  • Category (contains name and category Slug)
  • Final (contains group, tool, category, value1, value2)

The organization I put above would be the information menu. In this case, I would put the links in the categories. Then the route/link would be:

/grupo-selecionado/ferramenta-selecionada/categoria-selecionada

I wonder if I will need to organize my information manually or if it is possible to group this way using the ORM of Django.

1 answer

0

One way to solve this could be.

py.models

class Grupo(models.Model):
    titulo = models.CharField(max_length=20)

class Ferramenta(models.Model):
    titulo = models.CharField(max_length=20)
    grupo = models.ForeignKey(Grupo)

To have the visualization you mention in the question, it could be something like:

lista = Grupo.objects.prefetch_related('ferramenta_set').all()
for grupo in lista:
    print(grupo.titulo)
    for ferramenta in grupo.ferramenta_set.all():
        print(ferramenta.titulo)

It is simplified, but I hope that the principle is clear.

It’s worth a read in Django’s documentation about prefetch_related.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.