引用question 的答案中概述的方法也可以与 Flask-Admin-Dashboard 一起使用。
我在 Github 上创建了一个示例项目Flask-Admin-Dashboard-Summary。
以下是基本概念。
要显示汇总表,视图需要:
- 将汇总值注入视图
- 定义要使用的 Jinja 模板并适当修改它以使用注入的汇总值
设置 Jinja 模板
templates/admin/model/summary_list.html 是 list.html 的直接副本,来自 Flask-Admin Bootstrap 3 模板文件夹。
注意文件名summary_list.html,因为它在视图定义的render 方法中使用。
在第 163 行插入了以下 html 块:
{# This adds the summary data #}
{% for row in summary_data %}
<tr>
{% if actions %}
<td>
{# leave this empty #}
</td>
{% endif %}
{# This is the summary line title and goes in the action column, note that the action may not be visible!!! #}
{% if admin_view.column_display_actions %}
<td><strong>{{ row['title'] or ''}}</strong></td>
{% endif %}
{# This is the summary line data and goes in the individual columns #}
{% for c, name in list_columns %}
<td class="col-{{c}}">
<strong>{{ row[c] or ''}}</strong>
</td>
{% endfor %}
</tr>
{% endfor %}
设置视图
第 61 行,定义要使用的模板:
# don't call the custom page list.html as you'll get a recursive call
list_template = 'admin/model/summary_list.html'
第 75 行,覆盖视图的 render(self, template, **kwargs) 方法:
def render(self, template, **kwargs):
# we are only interested in the summary_list page
if template == 'admin/model/summary_list.html':
# append a summary_data dictionary into kwargs
# The title attribute value appears in the actions column
# all other attributes correspond to their respective Flask-Admin 'column_list' definition
_current_page = kwargs['page']
kwargs['summary_data'] = [
{'title': 'Page Total', 'name': None, 'cost': self.page_cost(_current_page)},
{'title': 'Grand Total', 'name': None, 'cost': self.total_cost()},
]
return super(ProjectView, self).render(template, **kwargs)
请注意第 66 行和第 71 行提供实际汇总数据的辅助方法,这些需要根据需要进行调整:
def page_cost(self, current_page):
# this should take into account any filters/search inplace
_query = self.session.query(Project).limit(self.page_size).offset(current_page * self.page_size)
return sum([p.cost for p in _query])
def total_cost(self):
# this should take into account any filters/search inplace
return self.session.query(func.sum(Project.cost)).scalar()