Search code examples
pythondjangomodels

Pattern to organize related items into groups


Let me try to explain what I want to achieve by a small example application. It is a shopping list application that lets you add predefined Items to your ShoppingList as Groceries. The smart thing would be that every Item is related to a Store.

model

When I am done adding groceries to my shopping list, I should be able to see my shopping list with the groceries organized (grouped) by their Store. Something like:

template

How would I create a view and template to group and display this shopping list?

For example: this is how I would display the full inventory of all stores:

#views.py
store_list = Store.objects.all()

#template.html
{% for store in store_list %}
<div>{{store}}
    <ul>
    {% for item in store.item_set.all %}
        <li>{{item}}</li>
    {% endfor %}
    </ul>
</div>
{% endfor %}

That won't work for my shopping list, but I am really looking for something equally powerful / elegant....


Solution

  • Do the grouping in the backend of the view instead of the template.

    In your view, create a dictionary like this:

    sorted_groceries = {
        store1 : [item1, item2],
        store2 : [item3, item4],
    }
    

    which can be done with some code resembling this pseudo-code:

    sorted_groceries = {}
    for item in shopping cart:
        try:
            sorted_groceries[item.store].append(item)
        except KeyError:
            sorted_groceries[item.store] = [item]
    

    then add it to your context and have your template look like this:

    {% for store, items in sorted_groceries.items %}
    <div>{{store}}
        <ul>
        {% for item in items %}
            <li>{{item}}</li>
        {% endfor %}
        </ul>
    </div>
    {% endfor %}