Search code examples
pythonodoo-11odoo-12

Return a list to Many2One field


I have a class Branch, class BranchLine, class Product, and class ReqTrans, the idea is to make a transfer request of products from one branch to another, what i want to do is when a user selects a certain branch, the available products should only be visible the classes are as follows

class CustomBranch(models.Model): 
    _name = 'custom.branch' 
    _description = 'Branch Record' 
    _rec_name = 'branch_name' 

    branch_name = fields.Char(string="Branch Name", required=False, ) 
    branch_line = fields.One2many('custom.branch.line', 'branch_id', string='Branch Lines', )

class CustomBranchLine(models.Model): 
    _name = 'custom.branch.line' 
    _description = 'Branch Line Record' 

    branch_id = fields.Many2one('custom.branch', string='Branch') 
    product_id = fields.Many2one('custom.product', string='Product') 
    qty = fields.Integer(string="QTY", required=False, )

class CustomTransRequest(models.Model): 
    _name = 'custom.trans.request' 
    _description = 'Transfer Request' 

branch_from_id = fields.Many2one('custom.branch', string="From") 
branch_to_id = fields.Many2one('custom.branch', string="To") 
product_ids = fields.Many2many('custom.product', string="Line") 

@api.onchange('branch_from_id') 
def onchange_branch_from(self): 
        for rec in self: 
            selected_lines = rec.env['custom.branch.line'].search([('branch_id', '=', rec.branch_from_id.id)]) 
            products = [] 
            for line in selected_lines: 
                 products.append([line.product_id.product_name, line.id]) 
        return products 

How do i return products to products_ids?


Solution

  • @api.onchange('branch_from_id') 
    def onchange_branch_from(self):
       for rec in self: 
          selected_products = rec.env['custom.branch.line'].search([('branch_id', '=', rec.branch_from_id.id)]).mapped('product_id')
          self.product_ids = [(6, 0, selected_products.ids)]
    

    Try this