odoo 一日一技 from odoo import Command 处理One2many和Many2many字段

基础介绍​​​

在Odoo(odoo14版本以上)中,Command类是用于处理One2many和Many2many字段。就是和之前命令元组相同,但是我觉得使用包装好的类能增加代码的可读性和简便性。

Command类中的方法和以往常量对比关系

CREATE = 0:创建新记录。
UPDATE = 1:更新现有记录。
DELETE = 2:删除记录。
UNLINK = 3:取消链接记录。
LINK = 4:链接记录。
CLEAR = 5:清除所有记录。
SET = 6:设置字段值为给定的记录列表。

代码示例

# 创建一个新的记录
values = {'name': 'New Record'}
create_command = Command.create(values)
print(create_command)  # 输出: (0, 0, {'name': 'New Record'})

# 更新一个现有的记录
record_id = 1
values = {'name': 'Updated Record'}
update_command = Command.update(record_id, values)
print(update_command)  # 输出: (1, 1, {'name': 'Updated Record'})

# 删除一个记录
record_id = 1
delete_command = Command.delete(record_id)
print(delete_command)  # 输出: (2, 1, 0)

# 取消链接一个记录
record_id = 1
unlink_command = Command.unlink(record_id)
print(unlink_command)  # 输出: (3, 1, 0)

# 链接一个记录
record_id = 1
link_command = Command.link(record_id)
print(link_command)  # 输出: (4, 1, 0)

# 清除所有记录
clear_command = Command.clear()
print(clear_command)  # 输出: (5, 0, 0)

# 设置一组新的记录
record_ids = [1, 2, 3]
set_command = Command.set(record_ids)
print(set_command)  # 输出: (6, 0, [1, 2, 3])

# 最后将command赋值给One2many和Many2many字段
## 创建示例 
self.api_params_ids = [
            Command.create({'name': 'test', 'path': 'test'}),
            Command.create({'name': 'test2', 'path': 'test2'}),
        ]

深入源码

Command源码地址

你可能感兴趣的:(odoo,odoo,一日一技)