简体   繁体   中英

How to show in Django queryset dict-key and -values seperately in template?

I have the this output in the browser from HTML template:

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

How can I show in an html template separately the key and the value(without saying Decimal)?

Desired outcome :

Bitcoin, 1498824
Ripple , 335227

I provide the query and the html template below:

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

Update template with below code:

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

Refer to this answer for removing decimal from result. Django: remove Decimal prefix from queryset annotated field, when requesting values

Try fetching both the key and the value from the dictionary in the loop:

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

If you want to format Decimal value see docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM