概要
主要介绍odoo中三种模型的使用场景以及使用方法。
模型
基本模型:models.Model
- 介绍:
models.Model
是最常见的模型类型,用于创建在数据库中存储数据的普通模型。 - 使用场景:适用于需要持久化存储数据的情况,如产品、客户、订单等。
- 使用方法:继承
models.Model
类,并定义模型的名称、字段、方法等。from odoo import models, fields class Product(models.Model): _name = 'my_module.product' name = fields.Char(string='Name', required=True) price = fields.Float(string='Price')
瞬态模型:models.TransientModel
- 介绍:
models.TransientModel
用于创建暂时性数据,不会永久存储在数据库中,而是在会话结束后自动销毁。 - 使用场景:适用于需要暂时性存储数据的情况,如临时计算结果、临时配置选项等,经常用在向导。
- 使用方法:继承
models.TransientModel
类,并定义模型的名称、字段、方法等。from odoo import models, fields class Wizard(models.TransientModel): _name = 'my_module.wizard' name = fields.Char(string='Name') date = fields.Date(string='Date')
抽象模型:models.AbstractModel
- 介绍:
models.AbstractModel
是一个抽象类,用于定义共享字段和方法但不会在数据库中创建表的模型。 - 使用场景:适用于多个模型需要共享通用字段和方法的情况,很适合方法封装。
- 使用方法:定义模型时继承
models.AbstractModel
,并定义模型的名称、字段、方法等。from odoo import models, fields class BaseProduct(models.AbstractModel): _name = 'my_module.base_product' _description = 'Base Product' name = fields.Char(string='Name', required=True) description = fields.Text(string='Description') class Product(models.Model): _name = 'my_module.product' _inherit = 'my_module.base_product' price = fields.Float(string='Price')
小结
多写多敲多思考,毕竟,知己知彼才能看懂源码。