3

Currently working on a e-commerce project (with django-oscar), I have an issue regarding products display on the basket template.

I use the {% regroup %} tag because I have several types of products : standalone, parent or children. Each basket line corresponds to a product, and if several of them are children sharing the same parent product, I want them to be regrouped under their common parent. However, I want standalone products to stand on their own.

My queryset is the following :

in_stock_lines = request.basket \
    .all_lines() \
    .order_by('product__parent', 'date_created') \
    .filter(attached_to=None, product__product_class__name='Produit standard', is_customized=False)

In basket.html:

{% regroup in_stock_lines by product.parent as parent_list %}
    {% for parent in parent_list %}
        {% if parent.grouper %}
            {% include "basket/partials/_basket_non_customized_product.html" %}
        {% else %}
            {% include "basket/partials/_basket_non_customized_standalone_product.html" %}
        {% endif %}
    {% endfor %}

The thing is that I don't want the regroup to act in the {% else %} part, because they are standalone products and are not supposed to be regrouped. But as their product.parent, i.e. the grouper is None, they are.

Is there way to prevent the {% regroup %} to act for a certain grouper value ? I could make two distinct queries in my views.py to separate standalone products from the others, and not include their template in the {% regroup %}, but I would like to avoid to make two queries if it can be.

Any help appreciated ! This is my first question on Stackoverflow, sorry if I miss some basic rules about the way I ask it.

gamabounta
  • 70
  • 8

1 Answers1

2

I don't think that is something you can do in the template directly. Django deliberately limits the 'tools' available in its template language to discourage putting too much logic in the templates.

Whilst you could do the work in views.py, as what you're doing is quite presentational, I would suggest a custom template tag (more specifically an inclusion tag) is probably what you want.

You should be able to avoid multiple queries as the grouping logic is quite simple. I'd suggest looking at collections.defaultdict for simple grouping.

Craig Loftus
  • 205
  • 1
  • 7