Model Reference(模型参考)
class odoo.models.Model(pool, cr)
常规的数据库持久性Odoo模型的主要父类。
通过继承这个父类来创建Odoo模型:
class user(Model):
...
系统稍后会在模型对应的模块安装之后实例化该Class。
模型结构属性
_name
业务对象(模型)名称,以点隔开(在模块命名空间中)
_rec_name
用作名称的替代字段,由osv的name_get()调用(默认值:‘name’)
_inherit
- 如果设置了_name,则继承的父模型的名称。如果从单个父级继承,则可以是***str***。
- 如果未设置_name,则为要扩展的单个模型的名称。
_order
在没有指定排序的情况下搜索时的排序字段(默认值:‘id’)
Type:
str
_auto
是否创建数据库表(默认值:True) 如果设置为False,则重写init()方法以创建数据库表
如需要创建没有表的模型,就需要继承 ***odoo.models.AbstractModel***来实现。
_table
支持_auto时创建的模型的表的名称,默认情况下自动生成。
_inherits
将父级模型的_name映射到要使用的相应外键字段的名称的字典:
_inherits = {
'a.model': 'a_field_id',
'b.model': 'b_field_id'
}
实现基于组合的继承:新模型可查询***_inherits-ed***模型的所有字段,但不存储它们:值本身。
依旧存储在链接记录中。
Warning!
多继承模型中存在相同字段。
_constraints
通过(constraint_function, message, fields)列表来定义Python约束。字段列表是指示性的。
Odoo 8.0 以后不推荐使用:使用约束 constrains()
_sql_constraints
通过(name,sql_definition,message)三元组列表,定义在生成表时要执行的SQL约束。
_parent_store
在parent_path字段旁边,设置记录树结构的索引存储,以使用child_of和parent_of域运算符对当前模型的记录启用更快的分层查询。 (默认值:False)
Type:
bool
CRUD(增删改查)
创建:create(vals_list) → records
为模型创建新记录。
使用字典***vals_list***列表中的值初始化新记录,如果需要,使用default_get()中的值。
Parameters
vals_list (list) –
values for the model’s fields, as a list of dictionaries:
[{‘field_name’: field_value, …}, …]
For backward compatibility, vals_list may be a dictionary. It is treated as a singleton list [vals], and a single record is returned.
Returns
the created records
Raises
AccessError –
if user has no create rights on the requested object
if user tries to bypass access rules for create on the requested object
ValidateError – if user tries to enter invalid value for a field that is not in selection
UserError – if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
查询:browse([ids]) → records
返回当前环境中作为参数提供的ID的记录集。
参数可以为空、单id或者id列表。
删除:unlink()
删除当前记录集的记录。
Raises:
AccessError –
if user has no unlink rights on the requested object
if user tries to bypass access rules for unlink on the requested object
UserError – if the record is default property for other records
更新:write(vals)
Parameters
vals (dict) –
fields to update and the value to set on them e.g:
{‘foo’: 1, ‘bar’: “Qux”}
will set the field foo to 1 and the field bar to “Qux” if those are valid (otherwise it will trigger an error).
Raises
AccessError –
if user has no write rights on the requested object
if user tries to bypass access rules for write on the requested object
ValidateError – if user tries to enter invalid value for a field that is not in selection
UserError – if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
- 对于数字字段(Integer, Float)值应该是对应的类型。
- 对于 Boolean, 值也应该是一个布尔值。
- 对于Selection,值应与选择值匹配(通常为str,有时为int)。
- 对于Many2one,该值应该是要设置的记录的数据库标识符(id)。
- 其他非关系字段使用字符串作为值
Warning!
出于历史和兼容性原因: Date 和 Datetime字段使用字符串作为值(写入和读取)而不是日期或日期时间。这些日期字符串仅限UTC,并根据odoo.tools.misc.DEFAULT_SERVER_DATE_FORMAT和odoo.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT格式化。
- One2many和Many2many使用特殊的“命令”格式来操作存储在字段中/与字段相关联的记录集。
此格式是按顺序执行的三元组列表,其中每个三元组是在记录集上执行的命令。并非所有命令都适用于所有情况。可能的命令是:
(0, _, values)
根据提供的字典值来创建一条新纪录。
(1, id, values)
根据已存在的记录id更新数据库记录值。不能使用 create()
(2, id, _)
根据id先从记录集中移除,然后在数据库中删除该记录。不能使用 create()
(3, id, _)
根据id从记录集中移除,但不会在数据库中删除该记录。不能用于One2many 字段。不能使用 create()
(4, id, _)
将id对应的数据库记录添加到记录集中。不能用于One2many 字段。
(5, _, _)
从记录集中删除所有记录,相当于在每条记录上明确执行命令3。不能使用 create()
(6, _, ids)
替换ids列表中对应记录集中的所有现有记录,相当于先执行命令5,后执行命令4,用于ids中的每个id。
read([fields])
从self 的记录中读取参数字段,low-level/RPC方法。在Python代码中,首选browse()。
Parameters
fields – list of field names to return (default is all fields)
Returns
a list of dictionaries mapping field names to their values, with one dictionary per record
Raises
AccessError – if user has no read rights on some of the given records
read_group(domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True)
获取按给定groupby字段分组的列表视图中的记录。
Parameters
domain – list specifying search criteria [[‘field_name’, ‘operator’, ‘value’], …]
fields (list) – list of fields present in the list view specified on the object. Each element is either ‘field’ (field name, using the default aggregation), or ‘field:agg’ (aggregate field with aggregation function ‘agg’), or ‘name:agg(field)’ (aggregate field with ‘agg’ and return it as ‘name’). The possible aggregation functions are the ones provided by PostgreSQL (https://www.postgresql.org/docs/current/static/functions-aggregate.html) and ‘count_distinct’, with the expected meaning.
groupby (list) – list of groupby descriptions by which the records will be grouped. A groupby description is either a field (then it will be grouped by that field) or a string ‘field:groupby_function’. Right now, the only functions supported are ‘day’, ‘week’, ‘month’, ‘quarter’ or ‘year’, and they only make sense for date/datetime fields.
offset (int) – optional number of records to skip
limit (int) – optional max number of records to return
orderby (list) – optional order by specification, for overriding the natural sort ordering of the groups, see also search() (supported only for many2one fields currently)
lazy (bool) – if true, the results are only grouped by the first groupby and the remaining groupbys are put in the __context key. If false, all the groupbys are done in one call.
Returns
list of dictionaries(one dictionary for each record) containing:
the values of fields grouped by the fields in groupby argument
__domain: list of tuples specifying the search criteria
__context: dictionary with argument like groupby
Return type
[{‘field_name_1’: value, …]
Raises
AccessError –
if user has no read rights on the requested object
if user tries to bypass access rules for read on the requested object
Searching(查询)
search(args[, offset=0][, limit=None][, order=None][, count=False])
基于***args*** 参数查询记录。
Parameters
args – A search domain. Use an empty list to match all records.
offset (int) – number of results to ignore (default: none)
limit (int) – maximum number of records to return (default: all)
order (str) – sort string
count (bool) – if True, only counts and returns the number of matching records (default: False)
Returns
at most limit records matching the search criteria
Raises
AccessError –
if user tries to bypass access rules for read on the requested object.
search_count(args) → int
根据查询条件返回当前模型中的记录数。
name_search(name=’’, args=None, operator=‘ilike’, limit=100) → records
与给定operator进行比较时,搜索具有与给定名称模式匹配的显示名称的记录,同时还匹配可选搜索域(args)。
这用于例如基于关系字段的部分值来提供建议。有时被视为*name_get()*的反函数,但不能保证。
name_search()方法等效于使用基于display_name的搜索域调用search(),然后在搜索结果上调用name_get()。
Parameters
name (str) – the name pattern to match
args (list) – optional search domain (see search() for syntax), specifying further restrictions
operator (str) – domain operator for matching name, such as ‘like’ or ‘=’.
limit (int) – optional max number of records to return
Return type
list
Returns
list of pairs (id, text_repr) for all matching records.
Recordset operations(记录集操作)
ids
此记录集中的实际记录ID列表(忽略要创建的记录的占位符ID)
ensure_one()
验证当前的recorset是否包含单个记录。否则会引发异常。
exists() → records
返回self中存在的记录子集,并在缓存中标记已删除的记录。它可以用作记录的测试:
if record.exists():
...
按照惯例,新记录将作为现有记录返回。
filtered(func)
在self中选择记录,取出func(rec)为true的筛选结果并将它们作为记录集返回。
Parameters:
func – a function or a dot-separated sequence of field names
sorted(key=None, reverse=False)
返回根据key排序的记录集。
Parameters
key – either a function of one argument that returns a comparison key for each record, or a field name, or None, in which case records are ordered according the default model’s order
reverse – if True, return the result in reverse order
mapped(func)
根据func 对self中的记录集进行取值筛选(如果func 返回的是一个记录集则返回记录集)。在后一种情况下,返回的记录集的顺序是任意的。
Parameters
func – a function or a dot-separated sequence of field names (string); any falsy value simply returns the recordset self
Environment swapping(环境中数据交换)
sudo([user=SUPERUSER])
返回附加提供的用户的此记录集的新版本。
默认情况下,它返回SUPERUSER记录集,其中绕过访问控制和记录规则。
使用sudo可能导致数据访问跨越记录规则的边界,可能混合要隔离的记录(例如,来自多公司环境中的不同公司的记录)。
这可能会导致在多种方法中选择一条记录的方法产生不直观的结果 - 例如获取默认公司或选择物料清单。
由于必须重新评估记录规则和访问控制,因此新记录集不会受益于当前环境的数据高速缓存,
因此以后的数据访问可能会在从数据库重新获取时产生额外的延迟。返回的记录集与self具有相同的预取对象。
with_context([context][, **overrides]) → records
返回的记录集拥有一个新的扩展其他属性的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}
with_env(env)
返回的记录集有一个新的上下文(context)。
Warning!
新环境不会受益于当前环境的数据缓存, 因此,以后的数据访问可能会在从数据库重新获取时产生额外的延迟。
返回的记录集与self具有相同的预取对象。
Fields and views querying(字段和视图查询)
fields_get([fields][, attributes])
返回每个字段的定义。
返回的值形式为字典中包含字典(由字段名称指示)。
继承的字段也包括在内。字符串,帮助和选择(如果存在)属性已翻译。
Parameters
allfields – 要记录的字段列表,如果为空或未提供,则全部为全部字段。
attributes – 要为每个字段返回的描述属性列表,如果为空或未提供,则全部返回属性。
fields_view_get([view_id | view_type=‘form’])**
获取所请求视图的详细组成结构,如字段,模型,视图体系结构。
Parameters:
view_id – 视图的ID或None
view_type – 如果view_id为None,则返回视图的类型(‘form’, ‘tree’, …)
toolbar – 如果包含上下文操作,则为true
submenu – 弃用
Returns:
描述所请求视图组成的字典 (包括继承的视图和扩展)
Raises:
AttributeError –
如果继承的视图具有未知的位置,可以使用‘before’, ‘after’, ‘inside’, ‘replace’以外的其他视图
如果在父视图中找到“position”以外的某些标记
Invalid ArchitectureError – 如果在结构上定义了窗体,树,日历,搜索等以外的视图类型
Miscellaneous methods(其他方法)
default_get(fields) → default_values
返回fields_list中字段的默认值。默认值由上下文,用户默认值和模型本身确定。
Parameters:
fields_list – 字段名称列表
Returns:
将每个字段名称映射到其对应的默认值的字典(如果有的话)。
copy(default=None)
根据默认值复制生成一条新纪录。
Parameters
default (dict) – dictionary of field values to override in the original values of the copied record, e.g: {‘field_name’: overridden_value, …}
Returns
new record
name_get() → [(id, name), …]
返回self中记录的文本表示。默认情况下,这是display_name字段的值。
Returns
list of pairs (id, text_repr) for each records
Return type
list(tuple)
name_create(name) → record
通过仅提供一个值调用create()来创建新记录:新记录的显示名称。
新记录将使用适用于此模型的任何默认值进行初始化,或通过上下文提供。 适用于create()的常用操作。
Parameters
name – display name of the record to create
Return type
tuple
Returns
the name_get() pair value of the created record
Automatic fields(模型自带字段)
id
标识符字段
_log_access
是否应生成日志访问字段(create_date,write_uid,…)(默认值:True)
create_date
创建记录的日期。
type:Datetime
create_uid
创建记录的用户。
Type res.users
write_date
上次修改记录的日期。
type:Datetime
write_uid
修改记录的最后一个用户。
Type res.users
Reserved field names(保留字段名称)
一些字段名称保留用于超出自动字段的预定义行为。当需要相关行为时,应在模型上定义它们:
name
_rec_name的默认值,用于在需要代表“命名”的上下文中显示记录。
Type: Char
active
切换记录的全局可见性,如果活动设置为False,则记录在大多数搜索和列表中不可见。
Type: Boolean
sequence
可更改的排序标准允许在列表视图中对模型进行拖放重新排序。
Type: Integer
state
对象的生命周期阶段,由fields属性上的属性使用。
Type: Selection
parent_id
用于在树结构中对记录进行排序,并在域中启用child_of和parent_of运算符。
Type: Many2one
parent_path
当_parent_store设置为True时,用于存储树结构的索引 - 必须使用index = True声明才能正常运行。
Type: Char