如何在Odoo视图域中按登录用户所属国家过滤res.partner记录?
嘿,我来帮你搞定这个问题!你碰到的Name 'user' is not defined错误,根源在于Odoo的XML动作定义里,直接写user是不被识别的,得用正确的方式引用当前登录用户的信息才行。
先看看你遇到的具体错误:
EvalError: Can not evaluate python expression: ({'user_country_id': user.partner_id.country_id.id})
Error: Name 'user' is not defined
EvalError: Can not evaluate python expression: ({'user_country_id': user.partner_id.country_id.id})
Error: Name 'user' is not defined
at evaluateExpr (http://localhost:8069/web/assets/debug/web.assets_web.js:32125:15)
at makeContext (http://localhost:8069/web/assets/debug/web.assets_web.js:18878:45)
at _preprocessAction (http://localhost:8069/web/assets/debug/web.assets_web.js:97579:26)
at doAction (http://localhost:8069/web/assets/debug/web.assets_web.js:98580:18)
at async Object.loadState (http://localhost:8069/web/assets/debug/web.assets_web.js:98886:13)
at async WebClient.loadRouterState (http://localhost:8069/web/assets/debug/web.assets_web.js:102973:27)
这个错误就是因为XML里的context表达式没法直接用user变量,得通过uid(Odoo内置的当前用户ID变量)来获取用户对象。下面给你两种可行的解决方案:
方案一:直接在Domain中写表达式(更简洁)
不用通过Context中转,直接在Domain字段里写完整的获取用户国家ID的表达式,修改你的action代码:
<record id="action_aefc_member_pending_approvals" model="ir.actions.act_window"> <field name="name">Pending User Approvals</field> <field name="res_model">res.partner</field> <field name="view_mode">list,form</field> <!-- 直接在domain中获取当前用户的国家ID --> <field name="domain">[('country_id', '=', env['res.users'].browse(uid).partner_id.country_id.id)]</field> <field name="view_id" ref="view_partner_list_approval"/> </record>
这里的uid是Odoo自动提供的当前登录用户ID,通过env['res.users'].browse(uid)就能拿到用户的完整记录,再链式获取关联的partner的country_id即可。
方案二:通过Context传递用户国家ID(保持你的原有思路)
如果你还是想保留Context传递的方式,那要修正Context里的表达式写法:
<record id="action_aefc_member_pending_approvals" model="ir.actions.act_window"> <field name="name">Pending User Approvals</field> <field name="res_model">res.partner</field> <field name="view_mode">list,form</field> <!-- 正确获取当前用户的国家ID并存入context --> <field name="context">{'user_country_id': env['res.users'].browse(uid).partner_id.country_id.id}</field> <field name="domain">[('country_id', '=', context.get('user_country_id'))]</field> <field name="view_id" ref="view_partner_list_approval"/> </record>
额外注意事项
- 要确保当前用户的关联
partner_id已经正确设置了country_id,不然会返回空值,导致过滤后没有显示任何记录。如果担心用户没设置国家,可以给表达式加个默认值,比如:env['res.users'].browse(uid).partner_id.country_id.id or False - 如果希望这个过滤规则对所有
res.partner视图生效(而不只是这个特定的action),推荐给res.partner模型添加记录规则(Record Rule):创建一个ir.rule记录,设置相同的Domain表达式,关联到对应的用户组,这样权限控制会更严谨。
备注:内容来源于stack exchange,提问作者japs




