odoo context上下文用法總結

授客發表於2023-03-05

環境

odoo-14.0.post20221212.tar

context用法總結

獲取上下文

>>> self.env.context # 返回字典資料,等價於 self._context
{'lang': 'en_US', 'tz': 'Europe/Brussels'}
>>> self._context
{'lang': 'en_US', 'tz': 'Europe/Brussels'}
>>> recordSet.env.context  # 注意,上下文是和記錄集繫結的,上述的self也代表記錄集

設定上下文

Model.with_context([context][, **overrides]) -> records[原始碼]

返回附加到擴充套件上下文的此記錄集的新版本。

擴充套件上下文是提供的合併了overridescontext,或者是合併了overrides當前context

# current context is {'key1': True}
r2 = records.with_context({}, key2=True)
# -> r2._context is {'key2': True}
r2 = records.with_context(key2=True)
# -> r2._context is {'key1': True, 'key2': True}

需要注意的是,上下文是和記錄集繫結的,修改後的上下文並不會在其它記錄集中共享

應用場景示例

用於action,為關聯檢視新增預設搜尋、過濾條件

檢視定義

為設定action開啟的tree列表檢視,新增預設搜尋,搜尋條件為 state欄位值等於True

<?xml version="1.0"?>
<odoo>
    <record id="link_estate_property_action" model="ir.actions.act_window">
        <field name="name">Properties</field>
        <field name="res_model">estate.property</field>
        <field name="view_mode">tree,form</field>
        <field name="context">{'search_default_state': True}</field>
    </record>

    <record id="estate_property_search_view" model="ir.ui.view">
        <field name="name">estate.property.search</field>
        <field name="model">estate.property</field>
        <field name="arch" type="xml">
            <search>
                <!-- 搜尋 -->
                <field name="name" string="Title" />               
                <separator/>
                <!-- 篩選 -->
                <filter string="Available" name="state" domain="['|',('state', '=', 'New'),('state', '=', 'Offer Received')]"></filter>               
            </search>
        </field>
    </record>
    <!--此處程式碼略...-->
</odoo>

說明:

<field name="context">{'search_default_fieldName': content}</field>

search_default_fieldName,其中fieldName 表示過濾器名稱,即搜尋檢視中定義的<field><filter>元素的name屬性值

content 如果fieldName為搜尋欄位<field>name屬性值,那麼content表示需要搜尋的內容,輸入內容是字串,則需要新增引號,形如'test';如果fieldName為搜尋過濾器<filter>name屬性值,那麼content表示布林值,該值為真,則表示預設開啟name所代表的過濾器,否則不開啟。

用於搜尋檢視,新增分組查詢條件

檢視設計
<?xml version="1.0"?>
<odoo>
    <!--此處程式碼略...-->
    <record id="estate_property_search_view" model="ir.ui.view">
        <field name="name">estate.property.search</field>
        <field name="model">estate.property</field>
        <field name="arch" type="xml">
            <search>                              
                <!-- 分組 -->
                <group expand="1" string="Group By">
                    <filter string="朝向" name="garden_orientation" context="{'group_by':'garden_orientation'}"/>
                </group>
            </search>
        </field>
    </record>
    <!--此處程式碼略...-->
</odoo>

說明:'group_by': '分組欄位名稱'

用於檢視物件按鈕,傳遞資料給模型方法

模型設計
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from odoo import models, fields, api

class EstatePropertyType(models.Model):
    _name = 'estate.property.type'
    _description = 'estate property type'

    name = fields.Char(string='name', required=True, help='help text')
    property_ids = fields.One2many('estate.property', 'property_type_id')
    offer_ids = fields.One2many('estate.property.offer', 'property_type_id')
    offer_count = fields.Integer(compute='_compute_offer_count')

    @api.depends('offer_ids.price')
    def _compute_offer_count(self):
        for record in self:
            record.offer_count = len(record.mapped('offer_ids.price'))
   
    @api.model
    def action_confirm(self, *args):
        print(self, self.env.context, args)
        # ... do something else
檢視設計
<?xml version="1.0"?>
<odoo>
    <!--此處程式碼略...-->
    <record id="estate_property_type_view_form" model="ir.ui.view">
        <field name="name">estate.property.type.form</field>
        <field name="model">estate.property.type</field>
        <field name="arch" type="xml">
            <form string="Property Type">
                <sheet>
                    <!--此處程式碼略...-->
                    <field name="offer_count">
                    <field name="property_ids">
                        <tree string="Properties">
                            <field name="name"/>
                            <field name="expected_price" string="Expected Price"/>
                            <field name="state" string="Status"/>
                        </tree>
                    </field>
                    <footer>
                       <button name="action_confirm" type="object" context="{'currentRecordID': active_id, 'offer_count':offer_count, 'property_ids': property_ids}" string="確認" class="oe_highlight"/>
                    </footer>
                </sheet>
            </form>
        </field>
    </record>
</odoo>

說明:context屬性值中的字典的鍵值如果為模型中定義的欄位名稱,則該欄位名稱必須以<field>元素的形式,出現在模型對應的檢視(即不能是內聯檢視,比如內聯Tree列表)中,否則會出現類似錯誤提示:

Field offer_count used in context.offerCount ({'offerCount': offer_count}) must be present in view but is missing.

點選介面按鈕後,服務端列印日誌如下

estate.property.type() {'lang': 'en_US', 'tz': 'Europe/Brussels', 'uid': 2, 'allowed_company_ids': [1], 'params': {'action': 165, 'cids': 1, 'id': 1, 'menu_id': 70, 'model': 'estate.property.type', 'view_type': 'form'}, 'currentRecordID': 1, 'offer_count': 4, 'property_ids': [[4, 49, False], [4, 48, False]]} ([1],)

說明:args 從日誌來看,args接收了當前記錄ID

注意:

  • 如果將def action_confirm(self, *args) 改成def action_confirm(self, arg),服務端控制檯會收到類似如下告警(雖然點選按鈕後,服務端不會拋異常):

    2023-02-06 01:28:53,848 28188 WARNING odoo odoo.addons.base.models.ir_ui_view: action_confirm on demo.wizard has parameters and cannot be called from a button
    
  • 如果將def action_confirm(self, *args)改成def action_confirm(self),則點選頁面確認按鈕時,服務端會報錯誤,如下:

    TypeError: action_confirm2() takes 1 positional argument but 2 were given
    

用於檢視動作按鈕,傳遞資料給動作關聯的檢視

檢視設計
<?xml version="1.0"?>
<odoo>    
    <!--此處程式碼略...-->
    <record id="estate_property_view_form" model="ir.ui.view">
        <field name="name">estate.property.form</field>
        <field name="model">estate.property</field>
        <field name="arch" type="xml">
            <form string="estate property form">
                <header>
                    <button name="%(action_demo_wizard)d" type="action" 
                    string="選取offers" context="{'is_force':True}" class="oe_highlight"/>
                    <!--此處程式碼略...-->     
                </sheet>
            </form>
        </field>
    </record>     
</odoo>

傳遞資料給檢視按鈕

action_demo_wizard action關聯檢視設計

<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <!--此處程式碼略...-->  
        <record id="demo_wizard_view_form" model="ir.ui.view">
            <field name="name">demo.wizard.form</field>
            <field name="model">demo.wizard</field>
            <field name="arch" type="xml">
                <form>                     
                    <!--此處程式碼略...-->  
                    <footer>                         
                       <button name="action_confirm" context="{'is_force':context.get('is_force')}" string="確認" class="oe_highlight"/>
                        <button string="關閉" class="oe_link" special="cancel"/>
                    </footer>
                </form>
            </field>
        </record>

        <!-- 透過動作選單觸發 -->
        <record id="action_demo_wizard" model="ir.actions.act_window">
            <field name="name">選取offers</field>
            <field name="res_model">demo.wizard</field>
            <field name="type">ir.actions.act_window</field>
            <field name="view_mode">form</field>
            <field name="target">new</field>
            <field name="binding_model_id" ref="estate.model_estate_property"/>
            <field name="binding_view_types">form</field>
        </record>       
    </data>
</odoo>

傳遞資料給檢視關係欄位

<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <data>
        <!--此處程式碼略...-->  
        <record id="demo_wizard_view_form" model="ir.ui.view">
            <field name="name">demo.wizard.form</field>
            <field name="model">demo.wizard</field>
            <field name="arch" type="xml">
                <form>
                    <field name="offer_ids" context="{'is_force':context.get('is_force')}" >
                        <tree>                            
                            <!--此處程式碼略...--> 
                        </tree>
                    </field>
                    <!--此處程式碼略...-->                      
                </form>
            </field>
        </record>

        <!-- 透過動作選單觸發 -->
        <record id="action_demo_wizard" model="ir.actions.act_window">
            <field name="name">選取offers</field>
            <field name="res_model">demo.wizard</field>
            <field name="type">ir.actions.act_window</field>
            <field name="view_mode">form</field>
            <field name="target">new</field>
            <field name="binding_model_id" ref="estate.model_estate_property"/>
            <field name="binding_view_types">form</field>
        </record>       
    </data>
</odoo>

用於檢視關係欄位,傳遞資料給模型方法

模型設計
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from odoo import models, fields

class EstateProperty(models.Model):
    _name = 'estate.property'
    _description = 'estate property table'

    name = fields.Char(required=True) 
    property_type_id = fields.Many2one("estate.property.type", string="PropertyType", options="{'no_create_edit': True}")
    offer_ids = fields.One2many("estate.property.offer", "property_id", string="PropertyOffer")
    
    # ...此處程式碼略  

    # 重寫父類read方法
    def read(self, fields=None, load='_classic_read'):
        print(self.env.context)
        property_type_id = self.env.context.get('propertyTypeId')
        if property_type_id:
            print('do something you want')
        return super(EstateProperty, self).read(fields, load)   
檢視設計
<?xml version="1.0"?>
<odoo>
    <!--此處程式碼略...-->
    <record id="estate_property_type_view_form" model="ir.ui.view">
        <field name="name">estate.property.type.form</field>
        <field name="model">estate.property.type</field>
        <field name="arch" type="xml">
            <form string="Property Type">
                <sheet>
                    <!--此處程式碼略...-->
                    <field name="property_ids" context="{'propertyTypeId': active_id}">
                        <tree string="Properties">
                            <field name="name"/>
                        </tree>
                    </field>
                    <!--此處程式碼略...-->
                </sheet>
            </form>
        </field>
    </record>
</odoo>

開啟上述檢視(即載入內聯Tree檢視)時,會自動呼叫estate.property模型的read方法,服務端控制檯輸出如下:

{'lang': 'en_US', 'tz': 'Europe/Brussels', 'uid': 2, 'allowed_company_ids': [1], 'params': {'action': 165, 'cids': 1, 'id': 1, 'menu_id': 70, 'model': 'estate.property.type', 'view_type': 'form'}, 'propertyTypeId': 1}
do something you want

更多示例可參考檔案:[odoo 為可編輯列表檢視欄位搜尋新增查詢過濾條件](odoo 為可編輯列表檢視欄位搜尋新增查詢過濾條件.md)

用於記錄集,傳遞資料給模型方法

模型設計
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from odoo import models, fields,api

class EstatePropertyTag(models.Model):
    _name = 'estate.property.tag'
    _description = 'estate property tag'

    name = fields.Char(string='tag', required=True)
    color = fields.Integer(string='Color')


    @api.model
    def create(self, vals_list): # 透過重寫模型的create或者write方法,呼叫該方法前修改上下文,然後在方法中透過self.env.context獲取上下文中的目標key值,進而實現目標需求
        res = super(EstatePropertyTag, self).create(vals_list)
        # 獲取上下文目標key值
        if not self.env.context.get('is_sync', True):
            # do something you need
        return res
>>> self.env['estate.property.tag'].with_context(is_sync=False).create({'name': 'tag4', 'color': 4}).env.context
{'lang': 'en_US', 'tz': 'Europe/Brussels', 'is_sync': False}

參考連線

https://www.odoo.com/documentation/14.0/zh_CN/developer/reference/addons/actions.html

相關文章