1.在Action中定义,context用于传递搜索条件和分组条件,在搜索视图中默认显示:

示例代码:

 <record model="ir.actions.act_window" id="open_company_allocation">
<field name="name">Leaves Summary</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
<field name="view_id" eval="view_holiday_simple"/>
<field name="context">{'search_default_group_type': 1, 'search_default_validated': 1}</field>
<field name="domain">[('holiday_type','=','employee')]</field>
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>
        <record model="ir.actions.act_window" id="open_company_allocation">
<field name="name">Leaves Summary</field>
<field name="res_model">hr.holidays</field>
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
<field name="view_id" eval="view_holiday_simple"/>
<field name="context">{'search_default_group_type': 1, 'search_default_validated': 1}</field>
<field name="domain">[('holiday_type','=','employee')]</field>
<field name="search_view_id" ref="view_hr_holidays_filter"/>
</record>

其中:

<field name="context">{'search_default_group_type': 1, 'search_default_validated': 1}</field>
定义了窗口打开时默认的分组条件 group_type 和过滤条件 validated ,如图所示:

对应的搜索视图代码:

<record id="view_hr_holidays_filter" model="ir.ui.view">
<field name="name">hr.holidays.filter</field>
<field name="model">hr.holidays</field>
<field name="arch" type="xml">
<search string="Search Leave">
<field name="name"/>
<separator/>
<filter icon="terp-check" domain="[('state','=','draft')]" string="To Confirm"/>
<filter icon="terp-camera_test" domain="[('state','in',('confirm','validate1'))]" string="To Approve" name="approve"/>
<filter icon="terp-camera_test" domain="[('state','=','validate')]" string="Validated" name="validated"/>
<separator/>
<filter icon="terp-go-year" name="year" string="Year" domain="[('holiday_status_id.active','=',True)]" help="Filters only on allocations and requests that belong to an holiday type that is 'active' (active field is True)"/>
<separator/>
<filter string="My Leaves" icon="terp-personal" name="my_leaves" domain="[('employee_id.user_id','=', uid)]" help="My Leaves"/>
<separator/>
<filter string="My Department Leaves" icon="terp-personal+" help="My Department Leaves" domain="[('department_id.manager_id','=',uid)]"/>
<field name="employee_id"/>
<field name="department_id"/>
<field name="holiday_status_id"/>
<group expand="0" string="Group By...">
<filter name="group_name" string="Description" domain="[]" context="{'group_by':'name'}"/>
<filter name="group_date_from" string="Start Date" icon="terp-personal" domain="[]" context="{'group_by':'date_from'}"/>
<filter name="group_employee" string="Employee" icon="terp-personal" domain="[]" context="{'group_by':'employee_id'}"/>
<filter name="group_category" string="Category" icon="terp-stock_symbol-selection" domain="[]" context="{'group_by':'category_id'}"/>
<filter string="Manager" icon="terp-personal" domain="[]" context="{'group_by':'manager_id'}"/>
<filter string="Department" icon="terp-personal+" domain="[]" context="{'group_by':'department_id','set_visible':True}"/>
<filter name="group_type" string="Type" icon="terp-stock_symbol-selection" domain="[]" context="{'group_by':'holiday_status_id'}"/>
<filter string="Status" icon="terp-stock_effects-object-colorize" domain="[]" context="{'group_by':'state'}"/>
</group>
</search>
</field>
</record>
        <record id="view_hr_holidays_filter" model="ir.ui.view">
<field name="name">hr.holidays.filter</field>
<field name="model">hr.holidays</field>
<field name="arch" type="xml">
<search string="Search Leave">
<field name="name"/>
<separator/>
<filter icon="terp-check" domain="[('state','=','draft')]" string="To Confirm"/>
<filter icon="terp-camera_test" domain="[('state','in',('confirm','validate1'))]" string="To Approve" name="approve"/>
<filter icon="terp-camera_test" domain="[('state','=','validate')]" string="Validated" name="validated"/>
<separator/>
<filter icon="terp-go-year" name="year" string="Year" domain="[('holiday_status_id.active','=',True)]" help="Filters only on allocations and requests that belong to an holiday type that is 'active' (active field is True)"/>
<separator/>
<filter string="My Leaves" icon="terp-personal" name="my_leaves" domain="[('employee_id.user_id','=', uid)]" help="My Leaves"/>
<separator/>
<filter string="My Department Leaves" icon="terp-personal+" help="My Department Leaves" domain="[('department_id.manager_id','=',uid)]"/>
<field name="employee_id"/>
<field name="department_id"/>
<field name="holiday_status_id"/>
<group expand="0" string="Group By...">
<filter name="group_name" string="Description" domain="[]" context="{'group_by':'name'}"/>
<filter name="group_date_from" string="Start Date" icon="terp-personal" domain="[]" context="{'group_by':'date_from'}"/>
<filter name="group_employee" string="Employee" icon="terp-personal" domain="[]" context="{'group_by':'employee_id'}"/>
<filter name="group_category" string="Category" icon="terp-stock_symbol-selection" domain="[]" context="{'group_by':'category_id'}"/>
<filter string="Manager" icon="terp-personal" domain="[]" context="{'group_by':'manager_id'}"/>
<filter string="Department" icon="terp-personal+" domain="[]" context="{'group_by':'department_id','set_visible':True}"/>
<filter name="group_type" string="Type" icon="terp-stock_symbol-selection" domain="[]" context="{'group_by':'holiday_status_id'}"/>
<filter string="Status" icon="terp-stock_effects-object-colorize" domain="[]" context="{'group_by':'state'}"/>
</group>
</search>
</field>
</record>

2.在Action中定义,context用于传递创建对象的默认值:

示例代码:XML中定义Action,context用于传递创建对象的默认值

<act_window
id="act_crm_opportunity_crm_phonecall_new"
name="Phone calls"
groups="base.group_sale_salesman"
res_model="crm.phonecall"
view_mode="tree,calendar,form"
context="{'default_duration': 1.0 ,'default_opportunity_id': active_id}"
view_type="form"/>
        <act_window
id="act_crm_opportunity_crm_phonecall_new"
name="Phone calls"
groups="base.group_sale_salesman"
res_model="crm.phonecall"
view_mode="tree,calendar,form"
context="{'default_duration': 1.0 ,'default_opportunity_id': active_id}"
view_type="form"/>

示例代码:Python后台代码中动态给Action的context赋值,context用于传递创建对象的默认值:

 def action_makeMeeting(self, cr, uid, ids, context=None):
"""
Open meeting's calendar view to schedule meeting on current opportunity.
:return dict: dictionary value for created Meeting view
"""
opportunity = self.browse(cr, uid, ids[0], context)
res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'base_calendar', 'action_crm_meeting', context)
res['context'] = {
'default_opportunity_id': opportunity.id,
'default_partner_id': opportunity.partner_id and opportunity.partner_id.id or False,
'default_partner_ids' : opportunity.partner_id and [opportunity.partner_id.id] or False,
'default_user_id': uid,
'default_section_id': opportunity.section_id and opportunity.section_id.id or False,
'default_email_from': opportunity.email_from,
'default_name': opportunity.name,
}
return res
    def action_makeMeeting(self, cr, uid, ids, context=None):
"""
Open meeting's calendar view to schedule meeting on current opportunity.
:return dict: dictionary value for created Meeting view
"""
opportunity = self.browse(cr, uid, ids[0], context)
res = self.pool.get('ir.actions.act_window').for_xml_id(cr, uid, 'base_calendar', 'action_crm_meeting', context)
res['context'] = {
'default_opportunity_id': opportunity.id,
'default_partner_id': opportunity.partner_id and opportunity.partner_id.id or False,
'default_partner_ids' : opportunity.partner_id and [opportunity.partner_id.id] or False,
'default_user_id': uid,
'default_section_id': opportunity.section_id and opportunity.section_id.id or False,
'default_email_from': opportunity.email_from,
'default_name': opportunity.name,
}
return res

其中:
context="{'default_duration': 1.0 ,'default_opportunity_id': active_id}"

res['context'] = {
  'default_opportunity_id': opportunity.id,
  'default_partner_id': opportunity.partner_id and opportunity.partner_id.id or False,
  'default_partner_ids' : opportunity.partner_id and [opportunity.partner_id.id] or False,
  'default_user_id': uid,
  'default_section_id': opportunity.section_id and opportunity.section_id.id or False,
  'default_email_from': opportunity.email_from,
  'default_name': opportunity.name,
}
定义了Action对应的对象创建新记录时的默认值。

3.在搜索视图中定义,context用于传递在视图中使用的变量:

示例代码:

<!-- CRM Lead Search View -->
<record id="view_crm_case_leads_filter" model="ir.ui.view">
<field name="name">CRM - Leads Search</field>
<field name="model">crm.lead</field>
<field name="arch" type="xml">
<search string="Search Leads">
<field name="name" string="Lead / Customer" filter_domain="['|','|',('partner_name','ilike',self),('email_from','ilike',self),('name','ilike',self)]"/>
<field name="categ_ids" string="Category" filter_domain="[('categ_ids','ilike',self)]"/>
<field name="section_id" context="{'invisible_section': False, 'default_section_id': self}"/>
<field name="user_id"/>
<field name="partner_id" filter_domain="[('partner_id','child_of',self)]"/>
<field name="create_date"/>
<field name="country_id" context="{'invisible_country': False}"/>
<separator/>
<filter string="Open" name="open" domain="[('state','!=','cancel')]" help="Open Leads"/>
<filter string="Dead" name="dead" domain="[('state','=','cancel')]"/>
<filter string="Unassigned" domain="[('user_id','=', False)]" help="No salesperson"/>
<filter string="Unread Messages" name="message_unread" domain="[('message_unread','=',True)]" help="Unread messages"/>
<filter string="Assigned to Me"
domain="[('user_id','=',uid)]" context="{'invisible_section': False}"
help="Leads that are assigned to me"/>
<filter string="Assigned to My Team(s)"
domain="[('section_id.member_ids', 'in', [uid])]" context="{'invisible_section': False}"
help="Leads that are assigned to any sales teams I am member of"/>
<separator />
<filter string="Available for mass mailing"
name='not_opt_out' domain="[('opt_out', '=', False)]"
help="Leads that did not ask not to be included in mass mailing campaigns"/>
<separator />
<group expand="0" string="Group By...">
<filter string="Salesperson" domain="[]" context="{'group_by':'user_id'}"/>
<filter string="Team" domain="[]" context="{'group_by':'section_id'}"/>
<filter string="Stage" domain="[]" context="{'group_by':'stage_id'}"/>
<filter string="Customer" help="Partner" domain="[]" context="{'group_by':'partner_id'}"/>
<filter string="Country" domain="[]" context="{'group_by':'country_id'}"/>
<filter string="Referrer" domain="[]" context="{'group_by':'referred'}"/>
<filter string="Campaign" domain="[]" context="{'group_by':'type_id'}"/>
<filter string="Channel" domain="[]" context="{'group_by':'channel_id'}"/>
<filter string="Creation" domain="[]" context="{'group_by':'create_date'}"/>
</group>
<group string="Display">
<filter string="Show Countries" context="{'invisible_country': False}" help="Show Countries"/>
<filter string="Show Sales Team" context="{'invisible_section': False}" domain="[]" help="Show Sales Team"/>
</group>
</search>
</field>
</record>
        <!-- CRM Lead Search View -->
<record id="view_crm_case_leads_filter" model="ir.ui.view">
<field name="name">CRM - Leads Search</field>
<field name="model">crm.lead</field>
<field name="arch" type="xml">
<search string="Search Leads">
<field name="name" string="Lead / Customer" filter_domain="['|','|',('partner_name','ilike',self),('email_from','ilike',self),('name','ilike',self)]"/>
<field name="categ_ids" string="Category" filter_domain="[('categ_ids','ilike',self)]"/>
<field name="section_id" context="{'invisible_section': False, 'default_section_id': self}"/>
<field name="user_id"/>
<field name="partner_id" filter_domain="[('partner_id','child_of',self)]"/>
<field name="create_date"/>
<field name="country_id" context="{'invisible_country': False}"/>
<separator/>
<filter string="Open" name="open" domain="[('state','!=','cancel')]" help="Open Leads"/>
<filter string="Dead" name="dead" domain="[('state','=','cancel')]"/>
<filter string="Unassigned" domain="[('user_id','=', False)]" help="No salesperson"/>
<filter string="Unread Messages" name="message_unread" domain="[('message_unread','=',True)]" help="Unread messages"/>
<filter string="Assigned to Me"
domain="[('user_id','=',uid)]" context="{'invisible_section': False}"
help="Leads that are assigned to me"/>
<filter string="Assigned to My Team(s)"
domain="[('section_id.member_ids', 'in', [uid])]" context="{'invisible_section': False}"
help="Leads that are assigned to any sales teams I am member of"/>
<separator />
<filter string="Available for mass mailing"
name='not_opt_out' domain="[('opt_out', '=', False)]"
help="Leads that did not ask not to be included in mass mailing campaigns"/>
<separator />
<group expand="0" string="Group By...">
<filter string="Salesperson" domain="[]" context="{'group_by':'user_id'}"/>
<filter string="Team" domain="[]" context="{'group_by':'section_id'}"/>
<filter string="Stage" domain="[]" context="{'group_by':'stage_id'}"/>
<filter string="Customer" help="Partner" domain="[]" context="{'group_by':'partner_id'}"/>
<filter string="Country" domain="[]" context="{'group_by':'country_id'}"/>
<filter string="Referrer" domain="[]" context="{'group_by':'referred'}"/>
<filter string="Campaign" domain="[]" context="{'group_by':'type_id'}"/>
<filter string="Channel" domain="[]" context="{'group_by':'channel_id'}"/>
<filter string="Creation" domain="[]" context="{'group_by':'create_date'}"/>
</group>
<group string="Display">
<filter string="Show Countries" context="{'invisible_country': False}" help="Show Countries"/>
<filter string="Show Sales Team" context="{'invisible_section': False}" domain="[]" help="Show Sales Team"/>
</group>
</search>
</field>
</record>

其中:
<filter string="Show Countries" context="{'invisible_country': False}" help="Show Countries"/> 
定义了在搜索视图中选择“显示国家”时,设置变量 invisible_country 的值为 False,tree 视图中引用变量,设置字段“国家”的显示或隐藏,
tree视图中的代码如下所示:
<field name="country_id" invisible="context.get('invisible_country', True)"/>

4.在Action中定义,context用于传递在后台搜索方法中使用的变量:

示例代码:

<act_window name="Related Products"
context="{'related_product':1}"
res_model="product.product"
src_model="product.product"
view_mode="tree,form"
key2="client_action_multi"
id="action_related_products2"/>
        <act_window name="Related Products"
context="{'related_product':1}"
res_model="product.product"
src_model="product.product"
view_mode="tree,form"
key2="client_action_multi"
id="action_related_products2"/>

其中:
context="{'related_product':1}"
定义了变量 related_product 的值为 1 ,后台代码中引用变量的代码如下所示:

from osv import osv, fields

class product_product(osv.osv):

    _inherit = 'product.product'

    def search(self, cr, uid, args=None, offset=0, limit=None, order=None,
context=None, count=False):
if context is None:
context = {} if context.get('related_product') and context.get('active_ids'):
bom_obj = self.pool.get('mrp.bom')
product_bom = bom_obj.search(cr,uid, [('product_id', 'in', context['active_ids'])])
parent_bom = [bom.bom_id.id for bom in
bom_obj.browse(cr,uid, product_bom) if bom.bom_id.id]
rel_ids = [bom.product_id.id for bom in bom_obj.browse(cr, uid, parent_bom)]
args.append(('id', 'in', rel_ids))
return super(product_product, self).search(cr,uid,args,offset,limit,
order,context=context, count=count) return super(product_product, self).search(cr,uid,args,offset,limit,
order,context=context, count=count)
product_product()
from osv import osv, fields

class product_product(osv.osv):

    _inherit = 'product.product'

    def search(self, cr, uid, args=None, offset=0, limit=None, order=None,
context=None, count=False):
if context is None:
context = {} if context.get('related_product') and context.get('active_ids'):
bom_obj = self.pool.get('mrp.bom')
product_bom = bom_obj.search(cr,uid, [('product_id', 'in', context['active_ids'])])
parent_bom = [bom.bom_id.id for bom in
bom_obj.browse(cr,uid, product_bom) if bom.bom_id.id]
rel_ids = [bom.product_id.id for bom in bom_obj.browse(cr, uid, parent_bom)]
args.append(('id', 'in', rel_ids))
return super(product_product, self).search(cr,uid,args,offset,limit,
order,context=context, count=count) return super(product_product, self).search(cr,uid,args,offset,limit,
order,context=context, count=count)
product_product()

后台代码中通过继承并覆写search方法,判断 context 中变量 related_product 的值,共用产品视图中实现了根据产品作为BOM的原料而生成的所有产品的的查询(列表)。

5.在后台代码中传递,context用于方法调用过程中变量的传递:

示例代码:

#写入,可用于校验写入和更改数据的合法性
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
if not context.get('set_to_draft', False): #非设置为草稿状态的操作
for rec in self.browse(cr, uid, ids, context=context):
if rec.state == 'draft' and rec.create_uid.id != uid:
raise osv.except_osv(_(u'警告!'),_(u'您不能修改他人创建的单据.'))
return super(dispatch_sale, self).write(cr, uid, ids, vals, context=context) #设置为草稿状态
def set_to_draft(self, cr, uid, ids, context=None):
ctx = context.copy()
ctx['set_to_draft'] = True #用于在write方法中判断是否是设置为草稿状态的操作
return self.write(cr, uid, ids, {'state': 'draft'}, ctx)
    #写入,可用于校验写入和更改数据的合法性
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
if not context.get('set_to_draft', False): #非设置为草稿状态的操作
for rec in self.browse(cr, uid, ids, context=context):
if rec.state == 'draft' and rec.create_uid.id != uid:
raise osv.except_osv(_(u'警告!'),_(u'您不能修改他人创建的单据.'))
return super(dispatch_sale, self).write(cr, uid, ids, vals, context=context) #设置为草稿状态
def set_to_draft(self, cr, uid, ids, context=None):
ctx = context.copy()
ctx['set_to_draft'] = True #用于在write方法中判断是否是设置为草稿状态的操作
return self.write(cr, uid, ids, {'state': 'draft'}, ctx)

其中:
set_to_draft 方法中定义了变量 ctx['set_to_draft'] = True 并作为参数传递到 write 中,
write 方法中判断变量的值 if not context.get('set_to_draft', False) 执行响应的业务逻辑。

openerp学习笔记 context 的应用的更多相关文章

  1. openerp学习笔记 webkit 打印

    1.webkit 打印需要安装的支持模块 请首先安装 Webkit 报表引擎(report_webkit),再安装 Webkit 报表的支持库(report_webkit_lib),该模块讲自动安装和 ...

  2. openerp学习笔记 计算字段支持搜索

    示例1: # -*- encoding: utf-8 -*-import poolerimport loggingimport netsvcimport toolslogger = netsvc.Lo ...

  3. openerp学习笔记 domain 增加扩展支持,例如支持 <field name="domain">[('type','=','get_user_ht_type()')]</field>

    示例代码1,ir_action_window.read : # -*- coding: utf-8 -*-from openerp.osv import fields,osv class res_us ...

  4. openerp学习笔记 自定义小数精度(小数位数)

    小数位数标识定义: lx_purchase/data/lx_purchase_data.xml <?xml version="1.0" encoding="utf- ...

  5. openerp学习笔记 跟踪状态,记录日志,发送消息

    跟踪状态基础数据: kl_qingjd/kl_qingjd_data.xml <?xml version="1.0"?><openerp>    <d ...

  6. openerp学习笔记 视图样式(表格行颜色、按钮,字段只读、隐藏,按钮状态、类型、图标、权限,group边距,聚合[合计、平均],样式)

    表格行颜色:             <tree string="请假单列表" colors="red:state == 'refuse';blue:state = ...

  7. openerp学习笔记 对象间关系【多对一(一对一)、一对多(主细结构)、多对多关系、自关联关系(树状结构)】

    1.多对一(一对一)关系:采购单与供应商之间的关系 'partner_id':fields.many2one('res.partner', 'Supplier', required=True, sta ...

  8. openerp学习笔记 domain 的应用

    1.在Action中定义,domain用于对象默认的搜索条件: 示例: <record id="action_orders" model="ir.actions.a ...

  9. openerp学习笔记 日期时间相关操作

    日期格式化字符串:DATE_FORMAT = "%Y-%m-%d" 日期时间格式字符串:DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" ...

随机推荐

  1. PHP7安装笔记

    PHP7安装笔记 时间 -- :: 喵了个咪 原文 http://www.hdj.me/php7-install-note 主题 PHP # 安装mcrypt yum install -y php-m ...

  2. c# 发送消息到Email

    /// <summary>        /// 发送消息到Email        /// </summary>        /// <param name=&quo ...

  3. 转载:PHP,MySQL的安装与配置

    本文转自:http://www.cnblogs.com/janas/archive/2012/08/27/2659240.html 一.安装配置PHP 1.下载Php的版本zip包之后,解压缩到指定目 ...

  4. XCODE快捷键个人总结

    1.在方法名上用CMD+左键 可以查看完整的方法名

  5. WCF分布式开发步步为赢(6):WCF服务契约继承与分解设计

    上一节我们学习了WCF分布式开发步步为赢(5)服务契约与操作重载部分.今天我们来继续学习WCF服务契约继承和服务分解设计相关的知识点.WCF服务契约继承有何优势和缺点?实际项目里契约设计有什么原则和依 ...

  6. poj 3662(经典最短路)

    题目链接:http://poj.org/problem?id=3662 思路:这题较多的有两种做法: 方法1:二分枚举最大边长limit,如果图中的边大于limit,则将图中的边当作1,表示免费使用一 ...

  7. Struts2 Convention插件的使用(1)

    刚刚查阅官方文档(convention-plugin.html)并学习了Struts2的Convention插件,文章这里只作为一个笔记,建议大家去看官方文档比较清晰和全面. 需要在项目添加这些包 c ...

  8. spring_150802_resource

    接口Service: package com.spring.service; public interface DogPetService { public void queryAllDogPets( ...

  9. lintcode:移动零

    题目 给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序 注意事项 1.必须在原数组上操作2.最小化操作数   样例 给出 nums = [0, 1, 0, 3, 1 ...

  10. Project Euler 106:Special subset sums: meta-testing 特殊的子集和:元检验

    Special subset sums: meta-testing Let S(A) represent the sum of elements in set A of size n. We shal ...