0

I want to check if a value is contained in a many2many field

my_own_m2m = fields.Many2many("a.table", string="My Own Many2many")

I tried with

for value in my_own_m2m :
    if (value.id == self.env.ref('some_external_id').id):
        hooray_i_found_it = True

Can we do it with something like

if self.env.ref('some_external_id').id in my_own_m2m:

I've tried it but cannot

strike_noir
  • 4,080
  • 11
  • 57
  • 100

1 Answers1

1

This should work:

if self.env.ref('some_external_id').id in my_own_m2m.mapped('id'):
    ...
forvas
  • 9,801
  • 7
  • 62
  • 158
  • can we do the same inside xml? for example in attrs="{'invisible':[(%('some_external_id')d,'not in','my_own_m2m.mapped('id')')]}" – strike_noir May 16 '18 at 11:51
  • No, in a domain (like the one used in `attrs`) it's mandatory to write a field name in the left part each tuple. – forvas May 16 '18 at 12:18
  • Can you give an example? I don't know how to write a field name in the left part each tuple – strike_noir May 16 '18 at 12:50
  • I mean that you can't put whatever in the left part of the tuples, like in your example, you're putting an integer (`%('some_external_id')d`). Instead you must write a field of the current model which is in the current XML view, e.g: `id` is a field each model has, so `attrs="{'invisible':[('id', 'not in', my_own_m2m.mapped('id'))]}"`. In this example, you must have written `` above, but in the same view. – forvas May 16 '18 at 13:04
  • First off `in my_own_m2m.ids` is enough, no need for `mapped`. And then the other thing. It could work with a domain like `[('my_own_m2m.ids', '=', ref('some_external_id'))]` but depends if `ref()` is usable in `attrs` domains, which i dont know at exact his moment ;-) – CZoellner May 16 '18 at 13:05
  • Another info: this domain style "x2many_field_ids = id_of_something" is like a reverse "in". You can read it as "id_of_something in x2many_field_ids". – CZoellner May 16 '18 at 13:07