如何在qweb report odoo 12中通过Python获取xml中模型的字段值?

问题描述

我想在 xml qweb 报告中获取模型的值。但在 xml 模型中,模型被视为字符串,因此不会对其进行迭代。 我的代码

def print_report_status(self):
        active_ids=self.env.context.get('active_ids',[])
        prd_categ= self.env['product.category'].search([])
        datas={
               'ids':active_ids,'model':'report.model','form' : self.read()[0],'categ':prd_categ,} 
        
        return self.env.ref('product_report.action_report_pr').report_action(self,data=datas)

并在 xml 中:

  <t t-foreach="categ"  t-as="c">
        <tr style="border:1px solid black;  text-align:left;">
                 <td width="20%" style="text-align:left;"><span t-field="c.name"/></td>
         </tr>
                    
   </t>

它正在考虑将“c”作为字符串而不是模型。 有什么建议请

解决方法

user10810227

您必须访问 data['categ'] 而不仅仅是 categ XML 中的 for-loop

,

我的回答特别不是关于为什么模型作为字符串返回,而是关于如何使这个报告工作。

  1. 您可以直接从 XML 查询模型并像这样在其中循环
<t t-foreach="request.env['product.category'].search([])"  t-as="c">
   <tr style="border:1px solid black;  text-align:left;">
       <td width="20%" style="text-align:left;"><span t-field="c.name"/>/td>
   </tr>
</t>
  1. 在我之前评论的第二种方法中,您可以使用 python 传递字典列表并在 XML 中循环它们。 类似的东西
def print_report_status(self):
    active_ids=self.env.context.get('active_ids',[])
    prd_categ= self.env['product.category'].search([])
    datas={
          'ids':active_ids,'model':'report.model','form' : self.read()[0],'categ': [{'name': i['name']} for i in prd_categ]
    } 
        
    return self.env.ref('product_report.action_report_pr').report_action(self,data=datas)

然后像以前一样在 XML 中循环数据。

,

我想你可以在你的 xml 模板中试试这个

<t t-set="categs" t-value="categ"/>
<t t-foreach="categs"  t-as="c">
    *something here*
</t>