odoo Model字段的参数
odoo Model字段的参数
class Field(object):
""" The field descriptor contains the field definition, and manages accesses
and assignments of the corresponding field on records. The following
attributes may be provided when instanciating a field:
:param string: the label of the field seen by users (string); if not
set, the ORM takes the field name in the class (capitalized).
:param help: the tooltip of the field seen by users (string)
:param readonly: whether the field is readonly (boolean, by default ``False``)
:param required: whether the value of the field is required (boolean, by
default ``False``)
:param index: whether the field is indexed in database (boolean, by
default ``False``)
:param default: the default value for the field; this is either a static
value, or a function taking a recordset and returning a value; use
``default=None`` to discard default values for the field
:param states: a dictionary mapping state values to lists of UI attribute-value
pairs; possible attributes are: 'readonly', 'required', 'invisible'.
Note: Any state-based condition requires the ``state`` field value to be
available on the client-side UI. This is typically done by including it in
the relevant views, possibly made invisible if not relevant for the
end-user.
:param groups: comma-separated list of group xml ids (string); this
restricts the field access to the users of the given groups only
:param bool copy: whether the field value should be copied when the record
is duplicated (default: ``True`` for normal fields, ``False`` for
``one2many`` and computed fields, including property fields and
related fields)
:param string oldname: the previous name of this field, so that ORM can rename
it automatically at migration
.. _field-computed:
.. rubric:: Computed fields
One can define a field whose value is computed instead of simply being
read from the database. The attributes that are specific to computed
fields are given below. To define such a field, simply provide a value
for the attribute ``compute``.
:param compute: name of a method that computes the field
:param inverse: name of a method that inverses the field (optional)
:param search: name of a method that implement search on the field (optional)
:param store: whether the field is stored in database (boolean, by
default ``False`` on computed fields)
:param compute_sudo: whether the field should be recomputed as superuser
to bypass access rights (boolean, by default ``False``)
The methods given for ``compute``, ``inverse`` and ``search`` are model
methods. Their signature is shown in the following example::
upper = fields.Char(compute='_compute_upper',
inverse='_inverse_upper',
search='_search_upper')
@api.depends('name')
def _compute_upper(self):
for rec in self:
rec.upper = rec.name.upper() if rec.name else False
def _inverse_upper(self):
for rec in self:
rec.name = rec.upper.lower() if rec.upper else False
def _search_upper(self, operator, value):
if operator == 'like':
operator = 'ilike'
return [('name', operator, value)]
The compute method has to assign the field on all records of the invoked
recordset. The decorator :meth:`odoo.api.depends` must be applied on
the compute method to specify the field dependencies; those dependencies
are used to determine when to recompute the field; recomputation is
automatic and guarantees cache/database consistency. Note that the same
method can be used for several fields, you simply have to assign all the
given fields in the method; the method will be invoked once for all
those fields.
By default, a computed field is not stored to the database, and is
computed on-the-fly. Adding the attribute ``store=True`` will store the
field's values in the database. The advantage of a stored field is that
searching on that field is done by the database itself. The disadvantage
is that it requires database updates when the field must be recomputed.
The inverse method, as its name says, does the inverse of the compute
method: the invoked records have a value for the field, and you must
apply the necessary changes on the field dependencies such that the
computation gives the expected value. Note that a computed field without
an inverse method is readonly by default.
The search method is invoked when processing domains before doing an
actual search on the model. It must return a domain equivalent to the
condition: ``field operator value``.
.. _field-related:
.. rubric:: Related fields
The value of a related field is given by following a sequence of
relational fields and reading a field on the reached model. The complete
sequence of fields to traverse is specified by the attribute
:param related: sequence of field names
Some field attributes are automatically copied from the source field if
they are not redefined: ``string``, ``help``, ``readonly``, ``required`` (only
if all fields in the sequence are required), ``groups``, ``digits``, ``size``,
``translate``, ``sanitize``, ``selection``, ``comodel_name``, ``domain``,
``context``. All semantic-free attributes are copied from the source
field.
By default, the values of related fields are not stored to the database.
Add the attribute ``store=True`` to make it stored, just like computed
fields. Related fields are automatically recomputed when their
dependencies are modified.
.. _field-company-dependent:
.. rubric:: Company-dependent fields
Formerly known as 'property' fields, the value of those fields depends
on the company. In other words, users that belong to different companies
may see different values for the field on a given record.
:param company_dependent: whether the field is company-dependent (boolean)
.. _field-sparse:
.. rubric:: Sparse fields
Sparse fields have a very small probability of being not null. Therefore
many such fields can be serialized compactly into a common location, the
latter being a so-called "serialized" field.
:param sparse: the name of the field where the value of this field must
be stored.
.. _field-incremental-definition:
.. rubric:: Incremental definition
A field is defined as class attribute on a model class. If the model
is extended (see :class:`~odoo.models.Model`), one can also extend
the field definition by redefining a field with the same name and same
type on the subclass. In that case, the attributes of the field are
taken from the parent class and overridden by the ones given in
subclasses.
For instance, the second class below only adds a tooltip on the field
``state``::
class First(models.Model):
_name = 'foo'
state = fields.Selection([...], required=True)
class Second(models.Model):
_inherit = 'foo'
state = fields.Selection(help="Blah blah blah")
"""
1.基础文件及目录结构
在认识odoo ORM框架前,先介绍一下odoo中模块目录结构。
data
:存放模块预制数据i18n
:存放国际化文件models
:存放模型等py代码security
:存放权限文件views
:存放视图文件__manifest__.py
:该文件用于声明该模块,并指定一些模块元数据。(odoo8时该文件为__openerp__.py
。)
# -*- coding: utf-8 -*-
{
# name:模块名称
'name': " test",
# description:模块描述
'description': """
自定义模块
""",
# author:模块作者(XXX公司或张三)
'author': "Hu",
# website:作者或公司网址
'website': "http://weibo.com/hcw1202",
# category:模块分类
'category': "test",
# version:模块版本
'version': "版本",
# depends:所依赖其他模块
'depends': ["base","stock","sale"],
# 模块安装时加载
'data': [
'security/权限文件.csv',
'data/预制数据.xml',
'views/视图文件.xml',
],
# 创建数据库时勾选Load demonstration data后安装该模块加载演示数据
'demo': [
'data/演示数据.xml',
],
}
2.Model属性
在/models下添加test.py
文件
# -*- coding: utf-8 -*-
from odoo import models, api, fields, _
class Test(models.Model):
# 模型唯一标识(对应数据表为product_manage_product)
_name = 'product_manage.product'
# 数据显示名称,如设置则返回其指定的字段值
_rec_name = 'test_field'
# 字段
test_field = fields.Char(string="字段名称")
model属性详解:_name
:模型唯一标识,类非继承父类时必须指定。_rec_name
:数据显示名称,如设置则返回其指定的字段值,不设置默认显示字段为name的字段值,如无name字段则显示"模块名,id";详见BaseModel.name_get
方法。_log_access
:是否自动增加日志字段(create_uid
, create_date
,write_uid
, write_date
)。默认为True。_auto
:是否创建数据库对象。默认为True,详见BaseModel._auto_init方法。_table
:数据库对象名称。缺省时数据库对象名称与_name指定值相同(.
替换为下划线)。_sequence
:数据库id字段的序列。默认自动创建序列。_order
:数据显示排序。所指定值为模型字段,按指定字段和方式排序结果集。
例:_order = "create_date desc":根据创建时间降序排列。可指定多个字段。
不指定desc默认升序排列;不指定_order默认id升序排列。
_constraints
:自定义约束条件。模型创建/编辑数据时触发,约束未通过弹出错误提示,拒绝创建/编辑。
格式:
_constraints = [(method, 'error message', [field1, ...]), ...]
method
:检查方法。返回True|False
error message
:不符合检查条件时(method返回False)弹出的错误信息
[field1, ...]
:字段名列表,这些字段的值会出现在error message中。
_sql_constraints
:数据库约束。
例:
_sql_constraints = [ ('number_uniq', 'unique(number, code)', 'error message') ]
会在数据库添加约束:
CONSTRAINT number_uniq UNIQUE(number, code)
_inherit
:单一继承。值为所继承父类_name标识。如子类不定义_name属性,则在父类中增加该子类下的字段或方法,不创建新对象;如子类定义_name属性,则创建新对象,新对象拥有父类所有的字段或方法,父类不受影响。
格式:
_inherit = '父类 _name'
_inherits
:多重继承。子类通过关联字段与父类关联,子类不拥有父类的字段或方法,但是可以直接操作父类的字段或方法。
格式:
_inherits = {'父类 _name': '关联字段'}
3.字段属性
基础类型
Char
:字符型,使用size参数定义字符串长度。Text
:文本型,无长度限制。Boolean
:布尔型(True,False)Interger
:整型Float
:浮点型,使用digits参数定义整数部分和小数部分位数。如digits=(10,6)
Datetime
:日期时间型Date
:日期型Binary
:二进制型selection
:下拉框字段。
例:
state = fields.Selection([('draft', 'Draft'),('confirm', 'Confirmed'),('cancel', 'Cancelled')], string='Status')
Html
:可设置字体格式、样式,可添加图片、链接等内容。效果如下:
截于odoo自带项目管理模块
关系类型
One2many
:一对多关系。
定义:
otm = fields.One2many("关联对象 _name", "关联字段",string="字段显示名",...
)
例:analytic_line_ids = fields.One2many('account.analytic.line', 'move_id', string='Analytic lines')"
Many2one
定义:
mto = fields.Many2one("关联对象 _name", string="字段显示名",...
)
可选参数:ondelete,可选值为‘cascade’和‘null’,缺省为null。表示one端删除时many端是否级联删除。
Many2many
定义:
mtm = fields.Many2many("关联对象 _name", "关联表/中间表","关联字段1","关联字段2",string="字段显示名"
,...)
其中,关联字段、关联表/中间表可不填,中间表缺省为:表1_表2_rel
例:partner_id= fields.Many2many("res.partner", string="字段显示名",...)"
复杂类型
参数
readonly
:是否只读,缺省值False。required
:是否必填,缺省值Falsse。string
:字段显示名,任意字符串。default
:字段默认值domain
:域条件,缺省值[]。在关系型字段中,domain用于过滤关联表中数据。help
:字段描述,鼠标滑过时提示。store
:是否存储于数据库。结合compute和related使用。
例:
sale_order = fields.One2many("sale.order", "contract_id",string="销售订单", domain=[('state','=','sale')])
compute
:字段值由函数计算,该字段可不储存于数据库。
例:
amount = fields.Float(string="金额总计", compute=‘_compute_amount’,store=True)
_compute_amount
为计算函数。
related
:字段值引用关联表中某字段。
以下代码表示:
company_id
引用hr.payroll.advice
中company_id
advice_id = fields.Many2one('hr.payroll.advice', string='Bank Advice')
company_id = fields.Many2one('res.company', related='advice_id.company_id',
string='Company', store=True)
4.最后
以上即是Model的主要属性,下一节会介绍Model中常用的方法
odoo Model字段的参数的更多相关文章
- Django model字段类型清单
转载:<Django model字段类型清单> Django 通过 models 实现数据库的创建.修改.删除等操作,本文为模型中一般常用的类型的清单,便于查询和使用: AutoField ...
- python-django 模型model字段类型说明
V=models.CharField(max_length=None<, **options>) #varchar V=models.EmailField(<max_length=7 ...
- Django中ORM介绍和字段及其参数
ORM介绍 ORM概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说,ORM是通过使用描述 ...
- Django模型层之字段查询参数及聚合函数
该系列教程系个人原创,并完整发布在个人官网刘江的博客和教程 所有转载本文者,需在顶部显著位置注明原作者及www.liujiangblog.com官网地址. 字段查询是指如何指定SQL WHERE子句的 ...
- Django model 字段类型及选项解析---转载
model field 类型1.AutoField() 自增的IntegerField,通常不用自己设置,若没有设置主键,Django会自动添加它为主键字段,Django会自动给每张表添加一个自增的p ...
- Django ORM中常用字段和参数
一些说明: 表myapp_person的名称是自动生成的,如果你要自定义表名,需要在model的Meta类中指定 db_table 参数,强烈建议使用小写表名,特别是使用MySQL作为后端数据库时. ...
- Django ORM 常用字段和参数
Django ORM 常用字段和参数 一:常用字段 AutoField int自增列,必须填入参数 primary_key=True.当model中如果没有自增列,则自动会创建一个列名为id的列. I ...
- url分发、isinstance、request.GET请求之QueryDict和urlencode、post和get请求、limit_choices_to(Model字段)
这个的路径是怎么来的,是有一个个的url路由分发过来的 这两个是相等的,若url后面加括号了,那么前面就不用这个装饰器了:反之,若装饰器使用了,那么这个url后面就不要加括号了 eg:其他的views ...
- django字段查询参数及聚合函数
字段查询是指如何指定SQL WHERE子句的内容.它们用作QuerySet的filter(), exclude()和get()方法的关键字参数. 默认查找类型为exact. 下表列出了所有的字段查询参 ...
随机推荐
- Java Web开发模式
一 Java Web开发模式的变迁 1 最初的Java web服务器端编程技术是Servlet,利用Servlet就可以开发出一个Web应用程序. 2 为了解决Servlet缺陷,SUN推出了JSP技 ...
- SLAM+语音机器人DIY系列:(二)ROS入门——9.熟练使用rviz
摘要 ROS机器人操作系统在机器人应用领域很流行,依托代码开源和模块间协作等特性,给机器人开发者带来了很大的方便.我们的机器人“miiboo”中的大部分程序也采用ROS进行开发,所以本文就重点对ROS ...
- 🕵️ 如何绕过 BKY 对 script 的屏蔽
Conmajia January 20, 2019 警告 这是试验,警告个屁,请不要多多尝试用它做多余的事. 果不其然,这篇文章立刻被移出主页了,我就说嘛,BKY 哪儿会那么包容和坦然呢? 原文 do ...
- Springboot 系列(十三)使用邮件服务
在我们这个时代,邮件服务不管是对于工作上的交流,还是平时的各种邮件通知,都是一个十分重要的存在.Java 从很早时候就可以通过 Java mail 支持邮件服务.Spring 更是对 Java mai ...
- [转]Windows10中Virtualbox没办法选择和安装64位的Linux系统
本文转自:https://blog.csdn.net/strivenoend/article/details/78290325 明明在公司的WIN7系统中使用Virtualbox就可以安装64位的Ub ...
- ASP.NET Core 基于JWT的认证(二)
ASP.NET Core 基于JWT的认证(二) 上一节我们对 Jwt 的一些基础知识进行了一个简单的介绍,这一节我们将详细的讲解,本次我们将详细的介绍一下 Jwt在 .Net Core 上的实际运用 ...
- Java笔记(day7-day8)
this关键字: (1)this(当局部变量和成员变量重名时,可以用关键字this区分) this代表对象,当前对象 this就是所在函数所属对象的引用 简单来说,哪个对象 ...
- Spring Boot Security 整合 JWT 实现 无状态的分布式API接口
简介 JSON Web Token(缩写 JWT)是目前最流行的跨域认证解决方案.JSON Web Token 入门教程 - 阮一峰,这篇文章可以帮你了解JWT的概念.本文重点讲解Spring Boo ...
- Eclipse4JavaEE配置Tomcat运行环境
如果我们想搭一个网站,我们可以使用Eclipse for JavaEE IDE进行开发. 初次使用需要配置网站的运行环境,可以去Apache官网下载Tomcat 8.5或Tomcat 9的版本 然后打 ...
- 洛谷P2664 树上游戏(点分治)
题意 题目链接 Sol 神仙题..Orz yyb 考虑点分治,那么每次我们只需要统计以当前点为\(LCA\)的点对之间的贡献以及\(LCA\)到所有点的贡献. 一个很神仙的思路是,对于任意两个点对的路 ...