首页 > 解决方案 > 如何在django模板的html表中显示多个对象数据

问题描述

我从视图向模板传递了两个查询集对象,它们都具有产品数据及其功能,现在主要问题是如何在 HTML 表中同时显示这两个对象数据?

表结构:

features1 | product1 features value 1 | product2 feature value 1
features2 | product1 features value 2 | product2 feature value 2
...
<tbody>                              
     {% for a in product_data %}{% for b in product_data_2 %}
         <tr class="row" style="line-height: 3">
              {% if forloop.counter == forloop.parentloop.counter %}
                    {% for feature_data in a.product_features.all %}{% for feature_data_1 in b.product_features.all %}
                        <td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: left; font-weight: bold;">
                             {{ feature_data.feature.feature_name }}
                         </td>
                        <td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: center;">
                             {{ feature_data.product_feature_value }}               
                         </td>                
                         <td class="col-lg-4 col-md-4 col-sm-4 col-4" style="text-align: center;">
                             {{ feature_data_1.product_feature_value }}
                         </td>
                    {% endfor %}{% endfor %}
              {% elif forloop.counter < forloop.parentloop.counter  %}
                    something
              {% elif forloop.parentloop.counter < forloop.counter  %}
                    something
              {% endif %}
          </tr>
     {% endfor %}{% endfor %}

 </tbody>                     

请尝试回答我试过但没有任何效果

标签: djangodjango-viewsdjango-templatesdjango-template-filters

解决方案


根据您的目的,您可以使用按索引with访问:

{% with first_obj=product_data.0 %}
{% with second_obj=product_data.1 %}
...
{% for feature_data in first_obj.product_features.all %}
   ...
{% endfor %}
{% for feature_data in second_obj.product_features.all %}
   ...
{% endfor %}

推荐阅读