Chapter 3: Models And Basic Fields
第三章:模型和基本字段
原文来自:
测试代码:https://gitee.com/zhang-wei918/estate
At the end of the previous chapter, we were able to create an Odoo module. However, at this point it is still an empty shell which doesn’t allow us to store any data. In our real estate module, we want to store the information related to the properties (name, description, price, living area…) in a database. The Odoo framework provides tools to facilitate database interactions.
在上一章节末尾,我们已经能够创建一个Odoo模块。但目前它仍是一个空壳,无法存储任何数据。在我们的房地产模块中,我们希望将与房产(名称、描述、价格、居住面积等)相关的信息存储在数据库中。Odoo框架提供了便于数据库交互的工具。
Before moving forward in the exercise, make sure the estate
module is installed, i.e. it must appear as ‘Installed’ in the Apps list.
在继续练习之前,请确保房地产模块已安装,即它应在应用列表中显示为“已安装”。
警告
Do not use mutable global variables. 不要使用可变的全局变量。
A single Odoo instance can run several databases in parallel within the same python process. Distinct modules might be installed on each of these databases, therefore we cannot rely on global variables that would be updated depending on installed modules.
一个Odoo实例可以在同一Python进程中并行运行多个数据库。这些数据库中的每一个可能安装了不同的模块,因此我们不能依赖于根据已安装模块更新的全局变量。
Object-Relational Mapping 对象关系映射
Reference: the documentation related to this topic can be found in the Models API.
参考:关于该主题的文档可在《模型API》中找到
注解
Goal: at the end of this section, the table estate_property
should be created:
目标:本节结束时,应创建名为estate_property的表:
$ psql -d rd-demo
rd-demo=# SELECT COUNT(*) FROM estate_property;
count
-------
0
(1 row)
A key component of Odoo is the ORM layer. This layer avoids having to manually write most SQL and provides extensibility and security services.
Odoo的一个关键组成部分是ORM层。这一层避免了手动编写大部分SQL,并提供了扩展性和安全性服务。
Business objects are declared as Python classes extending Model
, which integrates them into the automated persistence system.
业务对象作为Python类声明,通过继承Model,将其集成到自动持久化系统中。
Models can be configured by setting attributes in their definition. The most important attribute is _name
, which is required and defines the name for the model in the Odoo system. Here is a minimum definition of a model:
通过在模型定义中设置属性来配置模型。最重要的属性是_name,它是必需的,用于在Odoo系统中定义模型的名称。以下是模型的最小定义:
from odoo import models
class TestModel(models.Model):
_name = "test_model"
This definition is enough for the ORM to generate a database table named test_model
. By convention all models are located in a models
directory and each model is defined in its own Python file.
这个定义足以让ORM生成一个名为test_model的数据库表。按照惯例,所有模型都位于models目录中,每个模型都在其自己的Python文件中定义。
Take a look at how the crm_recurring_plan
table is defined and how the corresponding Python file is imported:
查看crm_recurring_plan表是如何定义的,以及相应的Python文件是如何导入的:
- The model is defined in the file
crm/models/crm_recurring_plan.py
(see here)
模型在文件crm/models/crm_recurring_plan.py
中定义(见此处) - The file
crm_recurring_plan.py
is imported incrm/models/__init__.py
(see here)crm_recurring_plan.py
文件在crm/models/__init__.py
中被导入(见此处) - The folder
models
is imported incrm/__init__.py
(see here)models
文件夹在crm/__init__.py
中被导入(见此处)
Exercise
Define the real estate properties model. 定义房地产属性模型。
Based on example given in the CRM module, create the appropriate files and folder for the estate_property
table.
根据CRM模块中的示例,为estate_property表创建适当的文件和文件夹。
When the files are created, add a minimum definition for the estate.property
model.
文件创建完成后,为estate.property
模型添加最小定义。
Any modification of the Python files requires a restart of the Odoo server. When we restart the server, we will add the parameters -d
and -u
:
对Python文件的任何修改都需要重启Odoo服务器。重启时,我们将添加参数-d和-u:
$./odoo-bin --addons-path=addons,../enterprise/,../tutorials/ -d rd-demo -u estate
-u estate
means we want to upgrade the estate
module, i.e. the ORM will apply database schema changes. In this case it creates a new table. -d rd-demo
means that the upgrade should be performed on the rd-demo
database. -u
should always be used in combination with -d
.
其中,-u estate意味着我们想要升级房地产模块,即ORM将应用数据库模式更改,在这种情况下它会创建一个新的表。-d rd-demo意味着升级应该在rd-demo数据库上执行。-u应始终与-d结合使用。
During the startup you should see the following warnings:
启动过程中,您应该看到以下警告:
…WARNING rd-demo odoo.models: The model estate.property has no _description
…WARNING rd-demo odoo.modules.loading: The model estate.property has no access rules, consider adding one…
…
If this is the case, then you should be good! To be sure, double check with psql
as demonstrated in the Goal.
如果出现上述警告,则说明操作正确!为了确认,可以按照目标所示使用psql进行检查。
Exercise
Add a description. 添加描述。
Add a _description
to your model to get rid of one of the warnings.
为您的模型添加_description以消除其中一个警告。
Model fields 模型字段
Reference: the documentation related to this topic can be found in the Fields API.
参考:关于该主题的文档可在《字段API》中找到。
Fields are used to define what the model can store and where they are stored. Fields are defined as attributes in the model class:
字段用于定义模型可以存储什么以及它们存储在哪里。字段作为模型类中的属性定义:
from odoo import fields, models
class TestModel(models.Model):
_name = "test_model"
_description = "Test Model"
name = fields.Char()
The name
field is a Char
which will be represented as a Python unicode str
and a SQL VARCHAR
.
name字段是一个Char,将表示为Python的unicode字符串和SQL的VARCHAR类型。
Types 类型
注解
Goal: at the end of this section, several basic fields should have been added to the table estate_property
:
目标:本节结束时,应向estate_property表添加几个基本字段:
$ psql -d rd-demo
rd-demo=# \d estate_property;
Table "public.estate_property"
Column | Type | Collation | Nullable | Default
--------------------+-----------------------------+-----------+----------+---------------------------------------------
id | integer | | not null | nextval('estate_property_id_seq'::regclass)
create_uid | integer | | |
create_date | timestamp without time zone | | |
write_uid | integer | | |
write_date | timestamp without time zone | | |
name | character varying | | |
description | text | | |
postcode | character varying | | |
date_availability | date | | |
expected_price | double precision | | |
selling_price | double precision | | |
bedrooms | integer | | |
living_area | integer | | |
facades | integer | | |
garage | boolean | | |
garden | boolean | | |
garden_area | integer | | |
garden_orientation | character varying | | |
Indexes:
"estate_property_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"estate_property_create_uid_fkey" FOREIGN KEY (create_uid) REFERENCES res_users(id) ON DELETE SET NULL
"estate_property_write_uid_fkey" FOREIGN KEY (write_uid) REFERENCES res_users(id) ON DELETE SET NULL
There are two broad categories of fields: ‘simple’ fields, which are atomic values stored directly in the model’s table, and ‘relational’ fields, which link records (of the same or different models).
字段分为两大类:“简单”字段,直接在模型表中存储原子值;和“关系”字段,链接记录(相同或不同模型的)
Simple field examples are Boolean
, Float
, Char
, Text
, Date
and Selection
.
简单字段的例子包括布尔值、浮点数、字符、文本、日期和选择。
Exercise
Add basic fields to the Real Estate Property table.
向房地产属性表添加基本字段。
Add the following basic fields to the table:
向表中添加以下基本字段:
Field | Type |
---|---|
name | Char |
description | Text |
postcode | Char |
date_availability | Date |
expected_price | Float |
selling_price | Float |
bedrooms | Integer |
living_area | Integer |
facades | Integer |
garage | Boolean |
garden | Boolean |
garden_area | Integer |
garden_orientation | Selection |
The garden_orientation
field must have 4 possible values: ‘North’, ‘South’, ‘East’ and ‘West’. The selection list is defined as a list of tuples, see here for an example.
garden_orientation字段应有4个可能的值:“北”,“南”,“东”和“西”。选择列表定义为元组列表,参见此处示例。
When the fields are added to the model, restart the server with -u estate
当字段添加到模型后,使用-u estate重启服务器。
$ ./odoo-bin --addons-path
=
addons,../enterprise/,../tutorials/ -d rd-demo -u estate
Connect to psql
and check the structure of the table estate_property
. You’ll notice that a couple of extra fields were also added to the table. We will revisit them later.
连接到psql并检查表estate_property的结构。您会注意到表中还添加了几项额外的字段。稍后我们将再次讨论它们。
Common Attributes 常见属性
注解
Goal: at the end of this section, the columns name
and expected_price
should be not nullable in the table estate_property
:
目标:本节结束时,表estate_property中的列name和expected_price应为非空:
rd-demo=# \d estate_property; Table "public.estate_property" Column | Type | Collation | Nullable | Default --------------------+-----------------------------+-----------+----------+--------------------------------------------- ... name | character varying | | not null | ... expected_price | double precision | | not null | ...
Much like the model itself, fields can be configured by passing configuration attributes as parameters:
与模型本身一样,字段可以通过传递配置属性作为参数来进行配置:
name = fields.Char(required=True)
Some attributes are available on all fields, here are the most common ones:
一些属性在所有字段上都可用,以下是其中最常用的几个:string
(str
, default: field’s name)
The label of the field in UI (visible by users).required
(bool
, default: False
)
string (str,默认:字段名) – 用户界面中字段的标签(用户可见)。
required
(bool
, default: False
)
If True
, the field can not be empty. It must either have a default value or always be given a value when creating a record.
required (bool,默认:False) – 如果为True,字段不能为空。它必须有一个默认值或在创建记录时总是赋予一个值。
help
(str
, default: ''
)
Provides long-form help tooltip for users in the UI.
help (str,默认:”) – 为用户提供UI中的长格式帮助提示。
index
(bool
, default: False
)
Requests that Odoo create a database index on the column.
index (bool,默认:False) – 请求Odoo在该列上创建数据库索引。
Exercise
Set attributes for existing fields. 为现有字段设置属性。
Add the following attributes: 添加以下属性:
Field 字段 | Attribute 属性 |
---|---|
name | required |
expected_price | required |
After restarting the server, both fields should be not nullable.
重启服务器后,这两个字段都应该是非空的。
Automatic Fields 自动字段
Reference: the documentation related to this topic can be found in Automatic fields.
参考:关于该主题的文档可在《自动字段》中找到。
You may have noticed your model has a few fields you never defined. Odoo creates a few fields in all models1. These fields are managed by the system and can’t be written to, but they can be read if useful or necessary:
您可能已经注意到,您的模型包含一些您从未定义过的字段。Odoo会在所有模型中创建一些字段。这些字段由系统管理,不能写入,但如果需要或必要,可以读取:
id
(Id
)
The unique identifier for a record of the model.
id (Id) – 模型记录的唯一标识符
create_date
(Datetime
)
Creation date of the record.
create_date (Datetime) – 记录的创建日期。
create_uid
(Many2one
)
User who created the record.
create_uid (Many2one) – 创建记录的用户。
write_date
(Datetime
)
Last modification date of the record.
write_date (Datetime) – 记录的最后修改日期。
write_uid
(Many2one
)
User who last modified the record.
write_uid (Many2one) – 最后修改记录的用户。
Now that we have created our first model, let’s add some security!
现在我们已经创建了第一个模型,接下来让我们增加一些安全性!
1.it is possible to disable the automatic creation of some fields
可以禁用某些字段的自动创建。
2.writing raw SQL queries is possible, but requires caution as this bypasses all Odoo authentication and security mechanisms.
编写原始SQL查询是可能的,但这需要谨慎,因为这绕过了所有Odoo的身份验证和安全机制。
发表回复