looping through a list of QuerySets in Template

Hi all, I’m fairly new to Django so apologies if what I’m trying to do makes little sense. Anyhow:

I’m extracting some products and for each product I have a bunch of orders (I don’t know how many)
to extract. Everything is then passed to a template, but I’m unable to loop through the sales.

Here’s the code from my view and my template, I think the issue is that I’m passing a list of QuerySets to my html template and I don’t know how to loop and access the various fields.

    product_list = Product.objects.filter(product_id=id)
           sales_data = []   #square brackets
           for product in product_list:
                if Sales.objects.filter(product_sold=product):

       return render(request, "sales/index.html", {
            "product_list": product_list, "sales_data ": sales_data 

in my html template:

{% for product in product_list %}


{% for sale in sales_data %}


{% endfor %}

{% endfor %}

I’m a beginner too, so please keep that in mind while I take a shot at helping. :grin:

I had a similar confusion recently — my notes in the sixth reply of this post (or the whole post) might be helpful: Context data and related_name (followers list) - #6 by StephanieAG

I’m not sure if this is “the” answer, but maybe it’s something to do with having the .all Django queryset function added in your template like this:

{% for product in product_list.all %}
{% for sale in sales_data.all %}

From your post, I’m unsure if you were saying just the sales_data for loop information isn’t showing on the template or both the product_list and the sales_data for loops weren’t coming through. Are they both not working or just the sales_data one?

it’s just the sales_data not working, I can see that the data is transferred to the template but I can’t find a way to work with it.

Basically I can see that is a QuerySet inside a list, so I can access single records with {{sale[0]}} but can’t loop or access specific fields.

I’ll have a look at your post, thanks for sharing

Try this instead:

{% for product in product_list %}
    {{ product.product_name }}
    {% for sale in sales_data %}
        {% for item in sale %}
            {{ item.keyword }}
            {{ item.another_keyword }}
        {% endfor %}
    {% endfor %}
{% endfor %}

Sale is actually a queryset (iterable)