spitfiredd
spitfiredd

Reputation: 3135

Flask: How do you access group by sum and counts in jinja2?

I am trying to get the values for a query:

total_sales =  (Model.query
                .with_entities(Model.dept_name,
                               sa.func.sum(Model.sales),
                               sa.func.count(Model.sales))
                .filter(Model.companyid == companyid)
                .filter(Model.sales> 0)
                .group_by(Model.companyid, Model.dept_name)
                .all())

In my jinja code I have:

{% for item in total_sales %}
             <tr>
                <td>{{ item.dept_name}}</td>
            </tr>
            <tr>
                <td>{{ item.sum }}</td>
            </tr>
            <tr>
                <td>{{ item.count }}</td>
            </tr>
        {% endfor %}

The dept_name shows up but the item.sum isn't showing and the item.count shows up as <built-in method count of result object at 0x000002DEA910D098>

If I print(total_sales) I can see the results of the query as a list of tuples. How do I access this in my jinja file?

Upvotes: 1

Views: 1069

Answers (1)

Luis Orduz
Luis Orduz

Reputation: 2887

You need to add labels to the function results so you can access them more clearly. Since you are using count and sum in the template, it'd be like:

sa.func.sum(Model.sales).label('sum'),
sa.func.count(Model.sales).label('count')

Upvotes: 4

Related Questions