Home > OS >  Django: Nested Loop In Template
Django: Nested Loop In Template

Time:10-03

category = ['cat1','cat2','cat3']
inventory = CurrentInventory.objects.all()
for cats in categories
    inventorybycat = inventory.filter(category =cats)
    setofinventories.append(inventorybycat)
dictofstuff = [zip(setofinventories,categories)]

context = {
 'setofinventories':setofinventories
 'category':category
 'dictofstuff':dictofstuff
 }

In views.py above this loop creates a list of objects per each category. In the template below this loop prints a filtered object list per every item in the category list.

{% for inventory in setofinventories%}
{% for item in inventory %}
{{ item.category }}
{{ item.productName }}
{% endfor %}
{% endfor %}

The only thing I am missing is I do not now how to reference the category in the template. I pass the whole list in context, but {{category{{forloop.counter}}}} is not a valid statement.

I would either like to use zip(category,setofinventories) to pass these two items together, or create a category model, filter by that model and then I can reference that model by item?

If I zip these items dictofstuff = [zip(setofinventories,categories)] How do I reference the category in the template?

{% for inventory,categories in dictofstuff %}
{% for inventory in setofinventories%}
{% for item in inventory %} 
{{ item.quantity }}
{{ item.productName }}
{% endfor %}
{% endfor %}
{% endfor %}

Returns Error: "Need 2 values to unpack in for loop: got 1."

CodePudding user response:

If i right understand you, you want to print category only one time. In your case:

{% for inventory in setofinventories%}

    {% ifchanged inventory.category %}
        {{ inventory.category }}
    {% endifchanged %}
    
    {% for item in inventory %}
        {{ item.quantity }}
        {{ item.productName }}
    {% endfor %}

{% endfor %}

i use ifchanged, more here: https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#ifchanged

CodePudding user response:

in views i zipped this to a *listofstuff. Forgive the nomenclature. dictofstuff = [zip(categories,setofinventories)]

in template. Again, forgive bad nomenclature. I should go back and rename these but it works.

{% for category in dictofstuff %}
{% for item in category %}
{{item.0}}   
{% for stuff in item %}
{% for thing in stuff %}
{{thing.productId}}{{thing.productName}}
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}
  • Related