Django regroup tag get fields values

Question:

I have a web page where I have two models for Products and Categories. I have this navbar where you can filter the Productos by categories, so in order to make it dynamic I passed the categories to the navbar and then applied a regroup since I’m getting the categories from the model Products since is the one the page is using to show the products.

When I try to filter catching the value from the regroup and pass it to my view:

class Categoria_Filter(ListView):
    model = Productos
    paginate_by = 10
    template_name = 'mail/category-filter.html'
    

    def get_queryset(self):
        categoria = self.kwargs['slug']
        print(categoria)
        if categoria == 'Todos':
            return Productos.objects.all()
        else:   
            return Productos.objects.filter(categoria = categoria)

I get the following result when printing:

GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>])

which according to the docs is a namedtuple()

I have tried the following:

print(getattr(categoria, 'GroupedResult'))
print(getattr(categoria, 'grouper'))
print(getattr(categoria, 'Categorias'))

They all give me:

AttributeError: 'str' object has no attribute 'whatever field I have tried'

Also, I print by index and for example:

print(categoria[1])

gives me

r

I know is the r from GroupedResult and what I want to get from the namedtuple is Guantes de Box not:

GroupedResult(grouper=<Categorias: Guantes de Box>, list=[<Productos: Guantes Básico ADX>])

This is the regroup in template:

{% regroup object_list by categoria as categoria_list %}
{% for item in categoria_list%}
<li class="nav-item">
    <a class="nav-link text-white" href="{% url 'categoria-filter' item %}">{{ item.grouper }}</a>
</li>
{% endfor %}
Asked By: Jorge López

||

Answers:

Based on the below line which you have in your get_queryset() of your class-based view:

categoria = self.kwargs['slug']

categoria is the value of 'slug' key in the request and of course it is an instance of str data type in python programming language.

But based on what I can find out from your question you need to Guantes de Box and with the below code and in {{ x.grouper }}, you can see the phrase Guantes de Box.

{% regroup object by object.property as newname %}

{% for x in newname %}
  {{ x.grouper }} --> this expression gives you the grouper names
  {% for y in x.list %}
    <p>{{ y.blobfield }}: {{ y.blobblobfield }}</p>
  {% endfor %}
{% endfor %}
Answered By: Javad