Skip to content Skip to sidebar Skip to footer

Django Template Filter Queryset

I'm new in django. I has a django application where stores products categorized by 'X' and 'Y'. views.py ... class CartListView(ListView): template_name = 'checkout/list.html' co

Solution 1:

First off, you should use IN operator over | when populating the filtered queryset:

defget_queryset(self):
    return Product.objects.filter(category__slug__in=["X", "Y"])

Secondly, you can't filter queryset by any field in the template unless you write a custom template tag which does that. However, it defeats the purpose of separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation. Thus, you need to override get_context_data and pass each queryset into the context:

defget_context_data(self, **kwargs):
    context = super(CartListView, self).get_context_data(**kwargs)

    context['minicurso'] = get_object_or_404(Category, slug='X')
    context['pacotes'] = get_object_or_404(Category, slug='Y')

    context["x_product_list"] = self.get_queryset().filter(category=context['minicurso'])
    context["y_product_list"] = self.get_queryset().filter(category=context['pacotes'])

    return context

Then you can use them in the template:

{% for category in x_product_list %}
  {{ category.name }}
{% endfor %}

...

{% for category in y_product_list %}
  {{ category.name }}
{% endfor %}

Post a Comment for "Django Template Filter Queryset"