Grouping values in Django

1

I'm having a bit of trouble putting together some information, from separate models.

For example: I have 3 models, one 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'd like to organize information like this:

  • Group Name 1

    • Tool Name 1

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

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

    • Tool Name 3

      • Category 7
      • Category 8
    • Tool Name 4

      • Category 9

Models

  • Group (contains group name and slug)
  • Tools (contains name and tool slug)
  • Category (contains category name and slug)
  • Final (contains group, tool, category, value1, value2)

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

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

I would like to know if I need to organize my information manually or whether it is possible to group it in this way using Django's own% .

    
asked by anonymous 16.01.2018 / 19:26

1 answer

0

One way to solve this could be like this.

models.py

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 preview you mention in the question 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's simplified, but I hope the principle has become clear.

It's worth reading the Django documentation on prefetch_related .

    
27.03.2018 / 18:05