场景:根据页面上的条件,查询报表,然后将生成的报表的作为附件附到当前页面
逻辑思路:
1、根据信息生成查询对象
2、根据自己定义的报表生成模型,查询到报表(ir.action.report)对象
3、利用render方法生成报表的二进制文件
4、将二进制文件关联到附件字段
代码如下(注意看代码注释)
def generate_report(self):
company_id = self.company_id
company_ids = []
budget_plan_id = self.budget_plan_id
report_search_data = {
'company_id': company_id.id,
'budget_plan_id': budget_plan_id.id
}
if self.budget_documents == 'profit':
# 生成查询对象
report_search_obj = self.env['hy.budget.profit.report'].create(report_search_data)
report_name = 'heyou_ext.budget_profit_report_xlsx'
elif self.budget_documents == 'group_profit':
report_search_obj = self.env['hy.budget.company.profit.report'].create(report_search_data)
report_name = 'heyou_ext.budget_company_profit_report_xlsx'
elif self.budget_documents == 'detail_profit':
report_search_obj = self.env['hy.budget.profit.detail.report'].create(report_search_data)
report_name = 'heyou_ext.budget_profit_detail_report_xlsx'
# 报表模型
report_obj = self.env["ir.actions.report"]
conditions = [(("report_name", "=", report_name))]
# 找到特定名称的报表对象,report_name:xml中定义报表report时的name属性
report = report_obj.with_context(self.env["res.users"].context_get()).search(conditions, limit=1)
# 生成二进制文件,本质上已经是报表文件了
file_data, file_type = report.with_context(report_search=True).render([report_search_obj.id], data={}, )
# 查询系统中是否有特定附件的方法
# attachment = self.env['ir.attachment'].sudo().search([
# ('res_model', '=', self._name),
# ('res_field', '=', 'attachment_binary'),
# ('res_id', '=', self.id),
# ], limit=1)
# 构建附件需要的参数
attachment_vals = {
'name': dict(self._fields['budget_documents']._description_selection(self.env)).get(self.budget_documents),
'type': 'binary',
'datas': base64.encodestring(file_data),
'res_model': self._name,
'res_field':'attachment_binary',
'res_id':self.id
}
self.attachment = None
# 创建附件对象
attachment = self.env['ir.attachment'].sudo().create(attachment_vals)
# 将生成的附件对象赋值到页面上的附件字段
self.attachment = attachment