odoo里API解读
Odoo自带的api装饰器主要有:model,multi,one,constrains,depends,onchange,returns 七个装饰器。
multi
multi则指self是多个记录的合集。因此,常使用for—in语句遍历self。
multi通常用于:在tree视图中点选多条记录,然后执行某方法,那么那个方法必须用@api.multi修饰,而参数中的self则代表选中的多条记录。
如果仅仅是在form视图下操作,那么self中通常只有当前正在操作的记录。
@api.multi
@api.depends('order_line.customer_lead', 'confirmation_date', 'order_line.state')
def _compute_expected_date(self):
""" For service and consumable, we only take the min dates. This method is extended in sale_stock to
take the picking_policy of SO into account.
"""
for order in self:
dates_list = []
confirm_date = fields.Datetime.from_string(order.confirmation_date if order.state == 'sale' else fields.Datetime.now())
for line in order.order_line.filtered(lambda x: x.state != 'cancel' and not x._is_delivery()):
dt = confirm_date + timedelta(days=line.customer_lead or 0.0)
dates_list.append(dt)
if dates_list:
order.expected_date = fields.Datetime.to_string(min(dates_list))
@api.multi
def write(self, vals):
res = super(Employee, self).write(vals)
return res
@api.multi
def unlink(self):
resources = self.mapped('resource_id')
super(Employee, self).unlink()
return resources.unlink()
model:方法里不写默认是:model
此时的self仅代表模型本身,不含任何记录信息。
@api.model
def create(self, vals):
if vals.get('name', _('New')) == _('New'):
if 'company_id' in vals:
vals['name'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code('sale.order') or _('New')
else:
vals['name'] = self.env['ir.sequence'].next_by_code('sale.order') or _('New') # Makes sure partner_invoice_id', 'partner_shipping_id' and 'pricelist_id' are defined
if any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id']):
partner = self.env['res.partner'].browse(vals.get('partner_id'))
addr = partner.address_get(['delivery', 'invoice'])
vals['partner_invoice_id'] = vals.setdefault('partner_invoice_id', addr['invoice'])
vals['partner_shipping_id'] = vals.setdefault('partner_shipping_id', addr['delivery'])
vals['pricelist_id'] = vals.setdefault('pricelist_id', partner.property_product_pricelist and partner.property_product_pricelist.id)
result = super(SaleOrder, self).create(vals)
return result
constrains
字段的代码约束。
@api.constrains('parent_id')
def _check_parent_id(self):
for employee in self:
if not employee._check_recursion():
raise ValidationError(_('You cannot create a recursive hierarchy.'))
depends
depends 主要用于compute方法,depends就是用来标该方法依赖于哪些字段的。
@api.depends('parent_group', 'parent_group.users', 'groups', 'groups.users', 'explicit_users')
def _compute_users(self):
for record in self:
users = record.mapped('groups.users')
users |= record.mapped('explicit_users')
users |= record.mapped('parent_group.users')
record.update({'users': users, 'count_users': len(users)})
@api.depends('order_line.price_total')
def _amount_all(self):
"""
Compute the total amounts of the SO.
"""
for order in self:
amount_untaxed = amount_tax = 0.0
for line in order.order_line:
amount_untaxed += line.price_subtotal
amount_tax += line.price_tax
order.update({
'amount_untaxed': order.pricelist_id.currency_id.round(amount_untaxed),
'amount_tax': order.pricelist_id.currency_id.round(amount_tax),
'amount_total': amount_untaxed + amount_tax,
})
onchange
onchange的使用方法非常简单,就是当字段发生改变时,触发绑定的函数。
@api.onchange('team_type')
def _onchange_team_type(self):
if self.team_type == 'sales':
self.use_quotations = True
self.use_invoices = True
if not self.dashboard_graph_model:
self.dashboard_graph_model = 'sale.report'
else:
self.use_quotations = False
self.use_invoices = False
self.dashboard_graph_model = 'sale.report'
return super(CrmTeam, self)._onchange_team_type()
returns
returns的用法主要是用来指定返回值的格式,它接受三个参数,第一个为返回值的model,第二个为向下兼容的method,第三个为向上兼容的method
@api.returns('self')
def _default_employee_get(self):
return self.env['hr.employee'].search([('user_id', '=', self.env.uid)], limit=1)
@api.model
@api.returns('self', lambda value: value.id if value else False)
def _get_default_team_id(self, user_id=None):
if not user_id:
user_id = self.env.uid
company_id = self.sudo(user_id).env.user.company_id.id
team_id = self.env['crm.team'].sudo().search([
'|', ('user_id', '=', user_id), ('member_ids', '=', user_id),
'|', ('company_id', '=', False), ('company_id', 'child_of', [company_id])
], limit=1)
if not team_id and 'default_team_id' in self.env.context:
team_id = self.env['crm.team'].browse(self.env.context.get('default_team_id'))
if not team_id:
default_team_id = self.env.ref('sales_team.team_sales_department', raise_if_not_found=False)
if default_team_id:
try:
default_team_id.check_access_rule('read')
except AccessError:
return self.env['crm.team']
if self.env.context.get('default_type') != 'lead' or default_team_id.use_leads and default_team_id.active:
team_id = default_team_id
return team_id
one
one的用法主要用于self为单一记录的情况,意思是指:self仅代表当前正在操作的记录。
@api.one
def _compute_amount_undiscounted(self):
total = 0.0
for line in self.order_line:
total += line.price_subtotal + line.price_unit * ((line.discount or 0.0) / 100.0) * line.product_uom_qty # why is there a discount in a field named amount_undiscounted ??
self.amount_undiscounted = total
odoo里API解读的更多相关文章
- Odoo : ORM API
记录集 model的数据是通过数据集合的形式来使用的,定义在model里的函数执行时它们的self变量也是一个数据集合 class AModel(models.Model): _name = 'a.m ...
- node.js(API解读) - process (http://snoopyxdy.blog.163.com/blog/static/60117440201192841649337/)
node.js(API解读) - process 2011-10-28 17:05:34| 分类: node | 标签:nodejs nodejsprocess node.jsprocess ...
- ODOO里视图开发案例---定义一个像tree、form一样的视图
odoo里视图模型MVC模式: 例子:在原来的视图上修改他: var CustomRenderer = KanbanRenderer.extend({ ....});var CustomRendere ...
- cdnbest的proxy里api用法案例:
用户的proxy帐号里api key要设置好,那个key设置后是不显示的,但会显示已设置 key是自已随便生成的 $uid = 22222; $skey = 'langansafe&*#'; ...
- 【转】odoo 新API装饰器中one、model、multi的区别
http://blog.csdn.net/qq_18863573/article/details/51114893 1.one装饰器详解 odoo新API中定义方式: date=fields.Date ...
- TravelPort官方API解读
TravelPort Ping通使用教程 Unit1 Lesson 1: 标签(空格分隔): 完成第1单元的三个课程后,您可以使用Travelport Universal API来提出服务请求并了解响 ...
- Odoo的@api.装饰器
转载请注明原文地址:https://www.cnblogs.com/cnodoo/p/9281437.html Odoo自带的api装饰器主要有:model,multi,one,constrains, ...
- odoo里的开发案例
1.模块命名[驼峰命名方法] res开头的是:resources 常见模型:res.users, res.company, res.partner, res.config.setti ...
- odoo里的rpc用法
import odoorpcdb_name = 'test-12'user_name = 'admin'password = 'admin'# Prepare the connection to th ...
随机推荐
- python pyyaml操作yaml配置文件
在测试工作中,可以使用yaml编写测试用例,执行测试用例时直接获取yaml中的用例数据进行测试(如:接口自动化测试) 1.什么是yaml 是一种可读的数据序列化语言,通常用于配置文件 非常简洁和强大, ...
- 【C++】Vector求最大值最小值
最大值: int max = *max_element(v.begin(),v.end()); 最小值: int min = *min_element(v.begin(),v.end());
- 摆脱鼠标之Dos学习
2015/12/24 for循环 1,创建文件 http://blog.csdn.net/wangxingbao4227/article/details/17009447 关于for循环的总结,很详细 ...
- Kubernetes 实战——有状态应用(StatefulSet)
一.简介 有状态实例:新实例和旧实例需要有相同的名称.网络标识和状态 无状态实例:可随时被替换 1. ReplicaSet 和有状态 Pod ReplicaSet 通过 Pod 模板创建多个 Pod ...
- SpringBoot数据访问(二) SpringBoot整合JPA
JPA简介 Spring Data JPA是Spring Data大家族的一部分,它可以轻松实现基于JPA的存储库.该模块用于增强支持基于JPA的数据访问层,它使我们可以更加容易地构建使用数据访问技术 ...
- SpringCloud Alibaba实战(6:nacos-server服务搭建)
源码地址:https://gitee.com/fighter3/eshop-project.git 持续更新中-- 大家好,我是三分恶. 这一节我们来学习SpringCloud Alibaba体系中一 ...
- 为什么代码规范要求SQL语句不要过多的join?
面试官:有操作过Linux吗? 我:有的呀 面试官:我想查看内存的使用情况该用什么命令 我:free 或者 top 面试官:那你说一下用free命令都可以看到啥信息 我:那,如下图所示 可以看到内存以 ...
- SCP,SSH应用
- Doris开发手记2:用SIMD指令优化存储层的热点代码
最近一直在进行Doris的向量化计算引擎的开发工作,在进行CPU热点排查时,发现了存储层上出现的CPU热点问题.于是尝试通过SIMD的指令优化了这部分的CPU热点代码,取得了较好的性能优化效果.借用本 ...
- 在Ubuntu 16.04中搭建RobotFramework环境
1.搭建RF环境 2.安装RF相关库 3.查看RF case 4.设置环境变量 相关知识点:pip --proxy=http://xx.xx.xx.xx:xx install 包名,使用pip的-- ...