gpt4 book ai didi

python - Flask 管理模型 - 摘要行

转载 作者:行者123 更新时间:2023-11-30 22:05:26 25 4
gpt4 key购买 nike

我正在使用 Flask Admin ( https://github.com/jonalxh/Flask-Admin-Dashboard ),但我有疑问。

假设我有一个模型:

产品

序列号

价格

我正在寻找一种方法来显示新行,以显示库存产品的总价。

有人能指出我正确的方向吗?

谢谢。

我已经对此进行了研究,但是当我显示自定义 View 时,我无法像在“标准”模型 View 上那样执行 CRUD 操作:How do you add a summary row for Flask-Admin?

P.S:我正在学习Python,所以如果这是一个基本问题,我正在浪费你的时间,请原谅我

最佳答案

引用question的答案中概述的方法也可以与 Flask-Admin-Dashboard 一起使用。

我创建了一个示例项目Flask-Admin-Dashboard-Summary在 Github 上。

Summary Rows for Project View

以下是基本概念。

要显示汇总表, View 需要:

  • 将汇总值注入(inject) View
  • 定义要使用的 Jinja 模板并对其进行适当修改以使用注入(inject)的摘要值

设置 Jinja 模板

templates/admin/model/summary_list.htmllist.html 的直接副本,来自 Flask-Admin Bootstrap 3 模板文件夹。

记下文件名 summary_list.html,因为它在 View 定义的 render 方法中使用。

以下 html block 已插入到第 163 行:

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

设置 View

第 61 行,定义要使用的模板:

# don't call the custom page list.html as you'll get a recursive call
list_template = 'admin/model/summary_list.html'

第 75 行,重写 View 的 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()

关于python - Flask 管理模型 - 摘要行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53017724/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com