How to render results from groupby query in html – Django

Issue

I’m trying to render results of a group by query from a view to an HTML table but it is returning nothing. I originally had success in listing all results, but after applying the sum aggregation I can’t get it to appear.

Django View – with Group By

def get_asset_price(request):
    # CryptoAssets is the model

    obj = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol')
    obj = obj.annotate(total_units=Sum('units'),
                  total_cost=Sum('cost'))\
        .order_by('symbol')

    # Returns list of dictionaries
    context = {
        'object': obj 
    }
    return render(request, 'coinprices/my-dashboard.html', context)

HTML

<style>
table, th, td {
  border: 1px solid black;
}
</style>
<div class="container">
      <h1>My Dashboard</h1>
    <table>
        <tr>
            <th>Symbol</th>
            <th>Total Units</th>
            <th>Total Cost</th>
        </tr>
        {% for row in object %}
        <tr>
            <td>{{ row.symbol }}</td>
            <td>{{ row.units }}</td>
            <td>{{ row.cost }}</td>
        </tr>
        {% endfor %}
    </table>
</div>
    {% endblock %}

I’ll provide the view below that worked without the group by.

Django View – No group by

def get_asset_price(request):
    # CryptoAssets is the model

    obj = CryptoAssets.objects.all().filter(user_id=request.user.id)

    # Returns list of objects
    context = {
        'object': obj
    }
    return render(request, 'coinprices/my-dashboard.html', context)

Solution

I think you’re calling an attribute which does not exist on your object. The type of your object is a list of dictionaries. Change your template codes to something like this (this is the simplest way and maybe you can improve it later like adding a template tag similar to the one that is used in this question):

<table>
    <tr>
        <th>Symbol</th>
        <th>Total Units</th>
        <th>Total Cost</th>
    </tr>
    {% for row in object %}
        <tr>
        {% for key, value in row.items %}
                <td>{{ key }}</td>
                <td>{{ value }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</table>

Answered By – Roham

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.