我们在写程序的时候经常会遇到这样的场景:
- 跳转视图的时候想要把当前视图的数据同时传递过去,在另一个视图直接使用
- 定义one2many字段时,把当前的数据传递到one2many字段的表直接使用
- 定义一个向导,将当前页面的数据传递到向导页面
- 跳转视图界面时进行默认搜索显示
此时我们就需要用到contex上下文了。context是一个字典
context={'字段名1':'字段值1','字段名2':'字段值2',}
1.获取context的方式:
- self._context 获取整个context
- self.env.context 获取整个context
- self._context.get('字段名') 获取context中指定字段的值
- self.env.context.get('字段名') 获取context中指定字段的值
2.设置修改context的值
保证context的字典类型 context = dict(context or {})
设置传递context的值 self.with_context({'字段名': '值'})
复制context的值 c = context.copy()
3.传递context的方式:
- 例如:按钮跳转视图时将当前模块记录的id传递过去,在其他视图界面通过接收值进行操作
<button name="%(purchase_management.act_window_purchase_application_wizard)d" string="退回修改" type="action" states="1_approval" class="oe_highlight"
context="{'model_id': active_id}"/>
- 菜单跳转视图界面时进行默认搜索显示(默认视图界面分组显示)
<record id="work_plan_act_window" model="ir.actions.act_window">
<field name="name">工作计划</field>
<field name="res_model">work.plan</field>
<!-- 设置默认分组-->
<field name="context">{'group_by': 'date:day'}</field>
<field name="search_view_id" ref="work_plan_search_view"/>
<field name="view_mode">tree,form,search</field>
</record>
- 按钮跳转视图界面时默认搜索显示(跳转到新界面后显示name为活动字段id的记录)
<button name="%(supplier_management.act_window_purchase_record_view)d" class="oe_stat_button"
icon="fa-th-list" type="action" groups="supplier_management.group_manager"
context="{'search_default_name': active_id, 'default_name': active_id, 'group_expand': True}"/>
- 给 one2many字段传递值
<field name="purchase_record_line" context="{'id': active_id, 'product_id': product_id, 'attribute': attribute}">
<tree editable="bottom">
<field name="order_id"/>
<field name="name"/>
<field name="category_id" invisible="1"/>
<field name="product_id" invisible="1"/>
<field name="attribute" invisible="1"/>
<field name="purchaser_id" invisible="1"/>
<field name="date"/>
<field name="quantity"/>
<field name="price" widget="monetary" options="{'currency_field': 'currency_id'}"/>
<field name="rate"/>
<field name="currency_id" invisible="1"/>
<field name="subtotal_tax" string="小计税额" invisible="1"/>
<field name="subtotal" string="小计" widget="monetary" options="{'currency_field': 'currency_id'}"/>
</tree>
</field>
使用 self._context.get('context_key_name') 获取传递的值
@api.onchange('name')
def _onchange_name(self):
# 根据供应商数据设置供应商分类默认值
for res in self.name:
if res.id:
self.product_id = self._context.get('product_id')
self.attribute = self._context.get('attribute')
self.order_id = self._context.get('id')
- 在self的记录集传递上下文(显示active=False的记录)
vals = self.env['supplier.management'].with_context(active_test=False).search([('id', '=', item)])
odoo上下文的用途非常广泛,这里我只简单的举了几个例子。相信理解了的话在其他场景也会很容易就能使用