【问题标题】:How to display multiple object data in html table in django template如何在django模板的html表中显示多个对象数据
【发布时间】:2020-06-13 20:35:23
【问题描述】:

我从视图向模板传递了两个查询集对象,它们都有产品数据及其特性现在主要问题是如何在 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>                     

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

【问题讨论】:

  • 有两种可能更简单的方法:1) 构建两个排序相似的单独表,并使用 css 水平对齐它们 2) 在视图中准备数据 - 构建一个包含所有需要值的单个行集直接输出。

标签: django django-views django-templates django-template-filters


【解决方案1】:

根据您的目的,您可以使用indexwith 的访问权限:

{% 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 %}

【讨论】:

  • 这仅显示我想要多个产品的 1 个功能
  • @Sahilshaikh 这显示了两种产品中每种产品的多个特征,因为您在循环中迭代特征(没有看到您的模型,我认为 product_features 是正确的属性)。
  • 是的,现在它提供了所有数据,但有 1 个问题,请查看问题并告诉我如何以给定格式在表格中显示数据!
  • 您没有提供足够的详细信息。所有产品都具有相同的功能集吗?如果不是,那么当功能不同时您想如何处理情况(无法显示没有其他产品具有的功能的产品的价值)。也许您需要先查询特征表以确定这两种产品的共同点。
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
相关资源
最近更新 更多