Search code examples
odooodoo-10odoo-9

Odoo 9/10 : How to get all childs ids of parents objects including their parents ids programmatically?


I have a many2many relation between res_users and product_category objects. So i defined it like this :

class ResPartner(models.Model):
    _inherit = 'res.partner'

    category_ids = fields.Many2many('product.category', 'category_user_rel', 'pcu_user_id', 'pcu_category_id', string='Assign To Product Categories')

class ProductCategory(models.Model):
    _inherit = 'product.category'

    user_ids = fields.Many2many('res.users', 'category_user_rel', 'pcu_category_id', 'pcu_user_id', string='Assign To Users')

Now, I want to get the list of all categories and their sub-categories ids for current user programmatically ?

Thanks.


Solution

  • You can get current user category_ids using the related partner to the current user:

    partner_categories = self.env.user.partner_id.category_ids
    

    Use child_of operator to retrieve all children categories:

    self.env['product.category'].search([('id', 'child_of', partner_categories.ids)])