Search code examples
pythonhtmldjangotastypie

How to include nested for loop in Django framework?


Hi I have two values lists as follows:

charts = group_obj.chartgroup.values_list('chart_info_id',flat=True).order_by("orderg", "-id")
order = group_obj.chartgroup.values_list('orderg', flat=True)

charts will print values: 1,2,3
order will print values: 9,8,7

passing the values to html as:

context['assigned_charts'] = charts
context['order'] = order

Am using this values_lists in my html (Django frame work and tastypie) as follows:

<div class="row">
        {% for c in assigned_charts %}
        <div class="col-md-{{colmd}}"  style="height: 550px; border:2px solid #CCC">
                <a class="pull-left" href="{% url 'update' c %}">{{ c }}</a>
            <div id="container{{c}}" style="height: 450px"></div>
        </div>
        {% endfor %}
</div>

Now am using only one of the values_list(charts). How can I use my second values_list(order) together with the first one? So that each chart will have their own corresponding order?


Solution

  • Multiple fields can be passed to values_list, you must remove flat=True.

    This will return a tuple that can be iterated over in the template like so:

    view:

    charts = group_obj.chartgroup.values_list('chart_info_id', 'orderg').order_by('orderg', '-id')
    context['assigned_charts'] = charts
    

    template:

    {% for chart, order in assigned_charts %}