首页 > 解决方案 > odoo 域搜索“id 中的 id”

问题描述

我有一个模型 B,它的 Many2many 字段引用模型 A。现在给定模型 A 的 id,我尝试获取引用它的 B 的记录。

Odoo 搜索域可以做到这一点吗?是否可以进行一些 SQL 查询?

例子

class A(models.Model):
    _name='module.a'

class B(models.Model):
    _name='module.b'
    a_ids = fields.Many2many('m.a')

我尝试做类似的事情

a_id = 5
filtered_b_ids = self.env['module.b'].search([(a_id,'in','a_ids')])

但是,这不是 Odoo 中的有效搜索。有没有办法让数据库进行搜索?到目前为止,我从数据库中获取了 B 的所有记录,然后过滤它们:

all_b_ids = self.env['module.b'].search([])
filtered_b_ids = [b_id for b_id in b_ids if a_id in b_id.a_ids]

但是,我想避免获取不需要的记录,并希望让数据库进行过滤。

标签: databaseodooodoo-11

解决方案


您应该在 A 中创建等效的 Many2many 字段。

class A(models.Model):
    _name='module.a'
    b_ids = fields.Many2many('module.b', 'rel_a_b', 'a_id', 'b_id')


class B(models.Model):
    _name='module.b'
    a_ids = fields.Many2many('module.a', 'rel_a_b', 'b_id', 'a_id')

在字段定义中,第二个参数是关联表的名称,接下来的两个是引用两个模型记录的列的名称。官方 ORM 文档中对此进行了解释。然后你只需要做my_a_record.b_ids

如果您更喜欢执行 SQL 请求,因为您不想将 python 字段添加到 A,您可以通过调用self.env.cr.execute("select id from module_b b, ...").fetchall(). 在您的请求中,您必须加入关联表(因此您需要为它及其列指定名称,如我的代码提取中所述,否则它们会由 Odoo 自动命名,我不知道规则)。

我认为仍然可以使用没有 A 中的字段的搜索域,但这很棘手。你可以试试search([('a_ids','in', [a_id])]),但我真的不确定。


推荐阅读