翼度科技»论坛 编程开发 python 查看内容

odoo 开发入门教程系列-模型和基本字段

7

主题

7

帖子

21

积分

新手上路

Rank: 1

积分
21
模型和基本字段

在上一章的末尾,我们创建一个odoo模块。然而,此时它仍然是一个空壳,不允许我们存储任何数据。在我们的房地产模块中,我们希望将与房地产相关的信息(名称(name)、描述(description)、价格(price)、居住面积(living area)…)存储在数据库中。odoo框架提供了数据库交互的工具
开始练习前,请确保estate模块已被安装,也就是说必须以installed的状态出现在Apps列表中,如下

对象关系映射(Object-Relational Mapping)

参考: 和本主题关联文档可参考 Models API.
ORM 层是odoo的一个关键组件。该层避免了手动写入大部分SQL并提供可扩展性和安全服务.
业务对象被定义为继承于 Model的Python类。可以通过在定义中设置属性来配置model。最重要的属性为 _name,该属性定义了model在odoo系统中的属性。以下为model的最小化定义:
  1. from odoo import models
  2. class TestModel(models.Model):
  3.     _name = "test.model"
复制代码
该定义足够ORM生成一张名为test_model的表。model _name中的 . 会被ORM自动化转为_ 。按约定所有的model位于一个名为  models 的目录,并且每个mode被定义为一个Python文件。
来看下 crm_recurring_plan 表是怎么定义的,以及对应Python文件是怎么导入的:

  • 在 odoo/addons/crm/models/crm_recurring_plan.py 中定义model(源码链接)
    1. # -*- coding: utf-8 -*-
    2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
    3. from odoo import fields, models
    4. class RecurringPlan(models.Model):
    5.     _name = "crm.recurring.plan"
    6.     _description = "CRM Recurring revenue plans"
    7.     _order = "sequence"
    8.     name = fields.Char('Plan Name', required=True, translate=True)
    9.     number_of_months = fields.Integer('# Months', required=True)
    10.     active = fields.Boolean('Active', default=True)
    11.     sequence = fields.Integer('Sequence', default=10)
    12.     _sql_constraints = [
    13.         ('check_number_of_months', 'CHECK(number_of_months >= 0)', 'The number of month can\'t be negative.'),
    14.     ]
    复制代码
  • 在crm/models/__init__.py中导入crm_recurring_plan.py (源码链接)
    1. # -*- coding: utf-8 -*-
    2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
    3. from . import res_users
    4. from . import calendar
    5. from . import crm_lead
    6. from . import crm_lost_reason
    7. from . import crm_stage
    8. from . import crm_team
    9. from . import ir_config_parameter
    10. from . import res_config_settings
    11. from . import res_partner
    12. from . import digest
    13. from . import crm_lead_scoring_frequency
    14. from . import utm
    15. from . import crm_recurring_plan
    复制代码
  • 在crm/__init__.py中导入models包 (源码链接)
    1. # -*- coding: utf-8 -*-
    2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
    3. from . import controllers
    4. from . import models
    5. from . import report
    6. from . import wizard
    7. from odoo import api, SUPERUSER_ID
    复制代码
练习

创建estate_property表的最小化模型

  • 在 odoo14/custom/estate/models/estate_property.py 中定义model
    1. #!/usr/bin/env python
    2. # -*- coding: utf-8 -*-
    3. from odoo import model
    4. class EstateProperty(models.Model):
    5.     _name = 'estate.property'
    复制代码
  • estate_property.py 在odoo14/custom/estate/models/__init__.py中导入
    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. from . import estate_property
    复制代码
  • 在estate/__init__.py中导入 models包
    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. from . import models
    复制代码
重启odoo服务
  1. python odoo-bin --addons-path=custom,odoo/addons -r myodoo -w test123 -d odoo -u estate
复制代码
-u estate 表示更新 estate 模块,也就是说ORM将应用数据库模式变更。
启动过程中可以看到类似以下告警日志:
  1. ...
  2. 2022-12-14 06:46:02,771 23792 WARNING odoo odoo.models: The model estate.property has no _description
  3. 2022-12-14 06:46:02,920 23792 WARNING odoo odoo.models: The model estate.property has no _description
  4. ...
  5. 2022-12-14 06:46:03,498 23792 WARNING odoo odoo.modules.loading: The model estate.property has no access rules, consider adding one...
  6. ...
  7. ...
复制代码
以防万一,可以看下到数据库看下表是否创建成功。pgAmin查看路径:Servers -> PostgreSQL 12 -> Databases (x) ->数据库名 -> Schemas -> public -> Tables
模型字段(Model Fields)

参考: 该主题相关文档可参考 Fields API
字段用于定义model可以存储啥及在哪里存储。 Fields被定义为model类的属性:
  1. from odoo import fields, models
  2. class TestModel(models.Model):
  3.     _name = "test.model"
  4.     _description = "Test Model"
  5.     name = fields.Char()
复制代码
name 字段被定义为Char,代表Python unicode的 str 和SQL的 VARCHAR.
有两大类领域字段:‘简单’字段--直接存储在模型表中的原子值,形如Boolean, Float, Char, Text, DateSelection, ‘关系型’ 字段--连接相同或者不同模型的记录。
给模型表estate_property添加字段
添加以下字段到表中
FieldTypenameChardescriptionTextpostcodeChardate_availabilityDateexpected_priceFloatselling_priceFloatbedroomsIntegerliving_areaIntegerfacadesIntegergarageBooleangardenBooleangarden_areaIntegergarden_orientationSelectionThe garden_orientation 字段必须有4种可选值:‘North’, ‘South’, ‘East’ 和‘West’。Selection(选择列表)定义为元组列表,查看示例
修改odoo14/custom/estate/models/estate_property.py文件
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from odoo import models,fields
  4. class EstateProperty(models.Model):
  5.     _name = 'estate.property'
  6.     _description = 'estate property table'
  7.     name = fields.Char(size=15)
  8.     description = fields.Text()
  9.     postcode = fields.Char(size=15)
  10.     date_availability = fields.Datetime('Availability Date')
  11.     expected_price = fields.Float('expected price', digits=(8, 2)) # 最大8位,小数占2位
  12.     selling_price = fields.Float('selling price', digits=(8, 2))
  13.     bedrooms = fields.Integer()
  14.     living_area = fields.Integer()
  15.     facades = fields.Integer()
  16.     garage = fields.Boolean('garage')
  17.     garden = fields.Boolean('garden')
  18.     garden_area = fields.Integer()
  19.     garden_orientation = fields.Selection(
  20.         string='Orientation',
  21.         selection=[('north', 'North'), ('south', 'South'), ('east', 'East'), ('West','West')],
  22.         help="garden orientation"
  23.     )
复制代码
重启odoo服务
  1. python odoo-bin --addons-path=custom,odoo/addons -r myodoo -w test123 -d odoo -u estate
复制代码
数据库中验证

常见属性

现在假设要求 name 和expected_price字段值不为null,所以需要对其修改,如下,添加字段属性配置required=True
  1. name = fields.Char(required=True)
  2. expected_price = fields.Float('expected price', digits=(8, 2),  required=True) # 最大8位,小数占2位
复制代码
修改后重启odoo服务。
有些属性是所有字段都拥有的,最常见的几个属性如下:

  • string (str, default: 字段名称)
    UI上显示为字段的label  (用户可见).
  • required (bool, default: False)
    如果为 True, 表示该字段值不能为空。创建记录时必须拥有默认值或给定的值。
  • help (str, default: '')
    UI上为用户提供long-form 帮助提示
  • index (bool, default: False)
    要求odoo在该列上创建数据库索引
自动创建的字段(Automatic Fields)

参考: 该话题相关文档可参考 Automatic fields.
odoo会在所有model(当然,也可以配置禁止自动创建某些字段)中创建少数字段。这些字段有系统管理并且不能写,但是可以读取,如果必要的话:

  • id (Id)
    model记录的唯一标识
  • create_date (Datetime)
    记录创建日期
  • create_uid (Many2one)
    记录创建人
  • write_date (Datetime)
    记录最后修改时间
  • write_uid (Many2one)
    记录最后修改人

来源:https://www.cnblogs.com/shouke/p/17253304.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具