Odoo的models.Model是Odoo框架中所有模型的基类,用于创建新的业务对象。它提供了ORM(对象关系映射)特性,使得开发者可以使用Python类来定义和操作数据库中的数据。models.Model中的字段是模型的核心组成部分,它们定义了数据的类型、行为和与其他模型的关系。
以下是Odoo模型中一些常用字段的类型和参数,以及代码示例:
字段类型:
Char - 用于存储短文本字符串。
Text - 用于存储长文本字符串。
Integer - 用于存储整数。
Float - 用于存储浮点数。
Boolean - 用于存储布尔值(True/False)。
Date - 用于存储日期。
DateTime - 用于存储日期和时间。
Binary - 用于存储二进制数据,如文件。
Selection - 用于创建选择列表。
Many2one - 用于创建对另一个模型的单个引用(外键)。
One2many - 用于表示反向的Many2one关系。
Many2many - 用于创建多对多关系。
字段参数:
string:字段的标签,用于在视图中显示。
required:设置字段是否为必填项。
readonly:设置字段是否可读写。
default:字段的默认值。
help:字段的帮助文本,用于向用户提供字段的详细描述。
index:是否为字段创建数据库索引,以提高查询效率。
代码示例:
from odoo import models, fields
class Book(models.Model):
_name = 'library.book'
_description = 'Library Book'
name = fields.Char(string='Title', required=True)
description = fields.Text(string='Description')
author_id = fields.Many2one('library.author', string='Author')
page_count = fields.Integer(string='Number of Pages')
price = fields.Float(string='Price')
currency_id = fields.Many2one('res.currency', string='Currency')
is_available = fields.Boolean(string='Available', default=True)
isbn = fields.Char(string='ISBN')
publish_date = fields.Date(string='Publish Date')
last_borrow_date = fields.Datetime(string='Last Borrow Date')
cover_image = fields.Binary(string='Cover Image')
genre_ids = fields.Many2many('library.genre', string='Genres')
class Author(models.Model):
_name = 'library.author'
_description = 'Author'
name = fields.Char(string='Name', required=True)
book_ids = fields.One2many('library.book', 'author_id', string='Books')
class Genre(models.Model):
_name = 'library.genre'
_description = 'Book Genre'
name = fields.Char(string='Name')
book_ids = fields.Many2many('library.book', string='Books')
在这个例子中,我们定义了三个Odoo模型:Book、Author和Genre。Book模型包含了多种字段,如Char、Text、Many2one、Integer、Float、Boolean、Binary和Many2many。我们也展示了如何使用字段参数,比如required和default。Author模型有一个One2many字段book_ids,它是与Book模型的Many2one字段author_id之间的反向关系。Genre模型使用Many2many字段与Book模型建立多对多关系