Domain of One2Many Child fields on the basis of parent fields
Today I was working on a module In Odoo11 where I needed to change the domain of a field in the tree view of One2many field on change of the parent field. I searched many things then I found a solution which I am going to explain in this tutorial. I will try to explain with an example how we are going to do so.
First, let us create the python code.
I am creating two models “parent.model” in which I am adding two fields. One field is M2O and the other is O2M. The other model is “child.model” in which I have added some fields. Let us see how we can change the domain of one of the fields in the child model(product_id) on the basis of parent module field(template_id). In this example, I haved added only those variants in the domain whose sale price is greater than 100. See the code below.
class ParentModel(models.Model):
_name = 'parent.model'
template_id = fields.Many2one('product.template',string='Template')
product_ids = fields.One2many(comodel_name = 'child.model', inverse_name = 'parent_id', string = 'Children Ids')
class ChildModel(models.Model):
_name= 'child.model'
parent_id = fields.Many2one(comodel_name='parent.model', string="Parent")
product_id = fields.Many2one(comodel_name='product.product', string="Product")
lst_price = fields.Float("Sale Price")
@api.onchange('product_id')
def onchange_product_id(self):
variant_ids_list = []
if self._context.get('template_id'): // We will pass this context from the xml view.
template_id = self.env["product.template"].browse(self._context.get('template_id'))
for variant_id in template_id.product_variant_ids:
if variant_id.lst_price > 100:
variant_ids_list.append(variant_id.id)
return result['domain'] = {'product_id': [('id','in',variant_ids_list)]
Now let us create the XML part.
<record id="parent_model_id" model="ir.ui.view">
<field name="name">parent.modle.form</field>
<field name="model">parnet.model</field>
<field name="arch" type="xml">
<form string="Parent Model" version="7.0">
<sheet>
<field name="template_id" />
<field name="product_ids" context="{'template_id':parent.template_id}"> # Pass the as context the field_name of the parent class using parent.field_name.
<tree editable="bottom" >
<field name="product_id" options="{'no_create_edit':True}"/>
<field name="lst_price"/>
</tree>
</field>
</sheet>
</form>
</field>
</record>
That is it.!!!
If you liked this post, It would be very grateful if you write your opinions, comments and suggestions to keep the post updated and interesting.
Thank you!