odoo15中x2many字段的操作

首先我们来回顾一下在14.0和之前的版本中,对于x2many字段的操作:

1
2
3
4
5
6
7
(0,0,{values}) 根据values里面的信息新建一个记录。
(1,ID,{values})更新id=ID的记录(写入values里面的数据)
(2,ID) 删除id=ID的数据(调用unlink方法,删除数据以及整个主从数据链接关系)
(3,ID) 切断主从数据的链接关系但是不删除这个数据
(4,ID) 为id=ID的数据添加主从链接关系。
(5) 删除所有的从数据的链接关系就是向所有的从数据调用(3,ID)
(6,0,[IDs]) 用IDs里面的记录替换原来的记录(就是先执行(5)再执行循环IDs执行(4,ID)

这种硬编码式的命令格式在15.0版本中得到了优化,这就是我们本篇文章的主题。

命令格式

为了方便记忆,官方在15.0对上面的集中命令格式进行封装。

命令符 解释 举例 命令结构
CREATE 根据values里的值创建一条新记录 Commmand.create({‘name’:’张三’}) (0,0,{values})
UPDATE 根据values的值更新id对应的记录 Command.update(1,{‘name’:’王心怡’}) (1,ID,{values})
DELETE 删除id=ID的这条记录 Command.delete(1) (2,ID)
UNLINK 切断主从关系,但不删除该数据 Command.unlink(1) (3,ID)
LINK 为id=ID的数据添加关联关系,3的反向操作 Command.link(1) (4,ID)
CLEAR 删除所有的主从关系,等价于循环调用记录集中的UNLINK方法 Command.clear() (5,)
SET 用IDS中的记录替换原来的记录, 等价于先使用CLEAR命令再循环调用LINK命令 Command.set([1,2,3]) (6,0,[IDS])

也就是说,从15.0开始,我们可以使用更贴近自然语言式的命令字来操作x2many字段了。

实战

下面我们就实际看一下如何使用新命令来替代之前的各种命令,首先我们启动shell环境,这里以开发手册中的书店模型为基础。

创建

1
2
3
4
5
>>> from odoo.fields import Command
>>> book = self.env['book_store.book'].create({"name":"巨人的陨落"})
>>> book.authors = [Command.create({"name":"肯*福莱特"})]
>>> book.authors
book_store.author(1,)

更新

1
2
3
>>> book.authors = [Command.update(1,{"name":"肯·福莱特"})]
>>> book.authors.name
'肯·福莱特'

删除

1
2
>>> book.authors = [Command.delete(1)]
2021-12-20 15:05:36,307 592958 INFO book_store odoo.models.unlink: User #1 deleted book_store.author records with IDs: [1]

连接

1
2
3
4
>>> author = self.env['book_store.author'].create({"name":"Kevin Kong"})
>>> book.authors = [Command.link(author.id)]
>>> book.authors.name
'Kevin Kong'

删除链接

1
2
3
>>> book.authors = [Command.unlink(author.id)]
>>> book.authors.name
False

清空

1
2
3
4
5
6
7
>>> authors = ["肯·福莱特","张三","Kevin Kong"]
>>> book.authors = [Command.create({"name":x}) for x in authors]
>>> book.authors.mapped("name")
['肯·福莱特', '张三', 'Kevin Kong']
>>> book.authors = [Command.clear()]
>>> book.authors.mapped("name")
[]

替换

1
2
3
4
5
6
7
8
9
>>> book.authors = [Command.create({"name":x}) for x in authors]
>>> book.authors.mapped("name")
['肯·福莱特', '张三', 'Kevin Kong']
>>> a = self.env['book_store.author'].create({"name":"马腾"})
>>> b = self.env['book_store.author'].create({"name":"李迅"})
>>> c = self.env['book_store.author'].create({"name":"周杰"})
>>> book.authors = [Command.set([a.id,b.id,c.id])]
>>> book.authors.mapped("name")
['马腾', '李迅', '周杰']

是不是方便了很多呢?

你的支持我的动力