我正在尝试获取查询的值:

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())


在我的Jinja代码中,我有:

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


显示的是dept_name,但没有显示item.sum,并且item.count显示为<built-in method count of result object at 0x000002DEA910D098>

如果我print(total_sales)我可以将查询的结果显示为元组列表。如何在Jinja文件中访问此文件?

最佳答案

您需要在函数结果中添加标签,以便可以更清晰地访问它们。由于您在模板中使用countsum,因此就像:

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

10-06 05:22
查看更多