環境
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[源代碼]
回傳附加到擴展背景關系的此記錄集的新版本,
擴展背景關系是提供的合并了overrides的context,或者是合并了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="確認" />
</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}" />
<!--此處代碼略...-->
</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="確認" />
<button string="關閉" 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
作者:授客
微信/QQ:1033553122
全國軟體測驗QQ交流群:7156436
Git地址:https://gitee.com/ishouke
友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!
作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額隨意,您的支持將是我繼續創作的源動力,打賞后如有任何疑問,請聯系我!!!
微信打賞
支付寶打賞 全國軟體測驗交流QQ群
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545843.html
標籤:其他
