【问题标题】:Odoo filtered one2manyOdoo 过滤了 one2many
【发布时间】:2019-08-27 17:12:23
【问题描述】:

我有一个带有one2many 字段mes_indicator_sub_group_ids 的模型。我试过了,但即使我知道有一条 id 为 5 的记录,也没有过滤任何内容:

  http.request.env['table.test'].sudo().search([('id', '=', int(category))]).filtered(lambda x: x.mes_indicator_sub_group_ids.ids in [5]) 

我需要过滤table.test 的记录,这些记录在mes_indicator_sub_group_ids 及其ID == 5. 中只有一条记录

编辑

我有一个模型model.mes_indicator_group,它包含两个one2many 字段,mes_indicator_sub_group_idsmes_indicator_ids。我想获得与 id=1 的model.mes_indicator_group 和 id=5 的mes_indicator_sub_group_ids 相关的记录集。例如,我想从first 组和fifth 子组中获取mes_indicator_ids。只是获取数据,而不是取消链接或写入。抱歉英语不好。

【问题讨论】:

  • 你能把你的代码,你的意思是什么,你会用它们做什么

标签: odoo odoo-11


【解决方案1】:

您要过滤one2many字段中只有一条记录且ID应为5的记录,只需确保长度为1且记录的ID为5:

http.request.env['table.test'].sudo().search(your_domain).filtered(lambda x: len(x.mes_indicator_sub_group_ids) == 1 and x.mes_indicator_sub_group_ids.id  == 5)

不用担心x.mes_indicator_sub_group_ids.id不会造成问题,因为它只包含一条记录。

这里的问题是,您在这种类型的域中使用 search([('id', '=', int(category))]),您将始终只有一条记录,如果您写一个 if statement 来解释您为您的团队所做的事情会更好,以及您何时处理使用ID 浏览更清晰:

   rec = http.request.env['table.test'].sudo().browse(int(category))
   if len(rec.mes_indicator_sub_group_ids) == 1 and rec.mes_indicator_sub_group_ids.id  == 5):
         # do what you need to do with this record

编辑

如果您想从数据库中完全删除它们,或者您 只是想将它们从 one2many 中删除,这取决于您。

    rec = http.request.env['table.test'].sudo().browse(int(category))
    # this remove all record from database keeps only record with 5
    rec.mes_indicator_sub_group_ids.filtered(lambda x : x.id != 5).unlink()  

    # this will remove the record from the one2many but keeps them in teh database
    rec.mes_indicator_sub_group_ids = [(6,0, [5])]

【讨论】:

  • 感谢您的回答。但是,如果我在您的三个示例之后添加 .mapped('mes_indicator_sub_group_ids') 并打印它,它会返回所有 mes_indicator_sub_group_ids 的记录集,而不仅仅是 id=5。
  • 对不起,我很困惑,我以为你想过滤 table.test 的记录,但现在我看到你只有一条记录,所以你需要过滤 indecator 记录。我注意到您使用了 id 这意味着您只有一条记录,您根本不必使用映射,只需过滤 one2many 直接的记录。检查我的编辑,我通过直接在 indecator 模型中搜索添加了另一个解决方案。
  • 再次感谢。很抱歉误导了你。但我真的很想过滤table.test的记录。然后在这个对象(table.test 只包含mes_indicator_sub_group_ids.ids =5)上调用另一个方法(存在于 table.test 中)。无论如何感谢您的帮助。
  • 首先令人困惑的是,我认为您要过滤 table.test 的记录,如果它是 indecator,则至少有一个 id 5。你想要这个还是要过滤 table.test 的记录,它只包含one2many 中的一条记录,id 为 5?或者你想要别的东西
  • 我想过滤 table.test 的记录,它只包含一个 id 为 5 的 one2many 中的一条记录
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多