Many-to-many relation filter

前端 未结 2 2012
萌比男神i
萌比男神i 2021-01-16 06:50

I need to filter my query with categories table which has many2many relation with another table. Is it possible to filter query with many2many relation?

Table

2条回答
  •  深忆病人
    2021-01-16 07:03

    As you already noticed, the many2one category_id is not represented in the database as a table field, but as a table relating Partners and Categories.

    The SQL you need could look like this:

    SELECT p.* 
    FROM res_partner p
      INNER JOIN res_partner_category_rel rel ON p.id = rel.partner_id
        INNER JOIN res_partner_category c ON rel.category_id = c.id
    WHERE c.id in (3,4)
    

    If you want to do the filter in the python object, the usual searchcall should work:

    list_ids = partner_model.search(cr, uid, [('category_id', 'in', [3,4])])
    

    As a bonus, since Categories are organized in a tree, you could get those categories and all their children using:

    list_ids = partner_model.search(cr, uid, [('category_id', 'child of', [3,4])])
    

提交回复
热议问题