【问题标题】:How to show in Django queryset dict-key and -values seperately in template?如何在模板中分别显示 Django queryset dict-key 和 -values?
【发布时间】:2021-08-13 05:00:42
【问题描述】:

我在浏览器中有来自 HTML 模板的这个输出:

{'coin__name': 'Bitcoin', 'total': Decimal('1498824')}
{'coin__name': 'Ripple', 'total': Decimal('335227')}

如何在 html 模板中分别显示键和值(不说十进制)?

期望的结果

Bitcoin, 1498824
Ripple , 335227

我在下面提供查询和 html 模板:

views.py:

test =  filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total')

template.html

<table class="table table-striped">
<tr>
    <th>Current dict pair</th>
    <th>Just the name of the crypto</th>
    <th>Just the price of the crypto</th>
</tr>
{% for item in test %}
<tr> 
    
    <td>{{ item }}</td>   
    <td>{{ }}</td>
    <td>{{ }}</td>

</tr>
{% endfor %}

【问题讨论】:

  • item.0item.1 给你什么?

标签: python django django-templates django-queryset django-template-filters


【解决方案1】:

使用以下代码更新模板:

            {{ test }}   <!--  test is list of dictonaries --> 
            <br>
            {% for item in test %} <!-- Loop to get each item(sub dictonary) from list-->
                <br>
                     {% for key,value in item.items %} <!-- Getting key values pairs from each sub dictonary item --> 
                        {% if forloop.last %} <!-- Checking if last iteration of loop just to add "::" after each value --> 
                            {{ value }} <!-- only displying values not keys from each sub dictionary -->
                        {%else%}
                            {{value }} , 
                        {% endif %}
                    {% endfor %}
                  
            {% endfor %}
        
    
    

请参阅此答案以从结果中删除小数。 Django: remove Decimal prefix from queryset annotated field, when requesting values

【讨论】:

  • 谢谢@Ashish Nautiyal。 :) 但是,我试图让它出现在一张整洁的桌子上。我不能,因为所有硬币价值对都出现在一列中。你能建议我如何修改表格吗?如果我在 HTML 代码中插入 &lt;td&gt;{{ value }}&lt;/td&gt;,所有硬币值对都会出现在一列中。
【解决方案2】:

尝试在循环中从字典中获取键和值:

{% for key, value in test.items %}
<tr> 
    <td>{{ key }}</td>   
    <td>{{ value }}</td>
</tr>
{% endfor %}

如果要格式化十进制值see docs

【讨论】:

    猜你喜欢
    • 2021-03-18
    • 2017-10-19
    • 2020-09-13
    • 2020-11-04
    • 2015-04-18
    • 2017-11-13
    • 2021-02-15
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多