简体   繁体   中英

How to filter out only the selected records in a Many2many field from all the other records in the model in odoo13 using domain filter

I am making a package model in which one can make packages and use it in the sales order, my model's name is sale.package.

class Package(models.Model):
    _name = 'sale.package'
    _description = 'Package table'

    name = fields.Char(string='Name', required=True)
    width = fields.Float(string='Width')
    height = fields.Float(string='Height')
    length = fields.Float(string='Length')
    maximum_weight = fields.Float(string='Maximum weight')

In order to use it in the sale order form, I inherited the sale.order model and added a Many2many field to the sale order which selects the previously made packages, I also created an Onchange function that updates an One2many field in a newly made page in the same sale order.

class SaleOrderPackage(models.Model):
    _inherit = 'sale.order'

    packs = fields.Many2many('sale.package', string='Package')
    package_lines = fields.One2many('sale.package.lines', 'line_name', string='Package Lines')

    @api.onchange('packs')
    def _onchange_packs(self):
        for rec in self:
            lines = [(5, 0, 0)]
            for line in self.packs:
                values = {
                    'name_on_line': line.name,
                    'line_width': line.width,
                    'line_height': line.height,
                    'line_length': line.length,
                    'line_maximum_weight': line.maximum_weight,
                }
                lines.append((0, 0, values))
            rec.package_lines = lines

Up to this everything is going fine, my new requirement is to add a smart button to the same sale order and upon clicking it, a tree view of the selected packages in the sale order must show up. I have added the smart button and defined a function in the python file which returns not only the selected but also all the packages made with the model.

    def selected_packages(self):
        print(self.packs)
        return {
            'name': 'Selected Packages',
            'domain': [],
            'view_type': 'form',
            'res_model': 'sale.package',
            'view_id': False,
            'view_mode': 'tree,form',
            'type': 'ir.actions.act_window'
        }

As I am only a week into learning Odoo I am unable to figure out how to use the domain filter in this context, Please help. Thanks in advance.

If you need to show only the selected packages, You have just to filter records using their id.

Use self.packs.ids to return the list of actual record ids corresponding to selected packages:

'domain': [('id', 'in', self.packs.ids)],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM