What's the difference between delegate on Many2one fields and _inherits in odoo15?

Viewed 95

Actually, I have two questions:

The first one: Is there any difference between the following code snippet?

class Pallet(models.Model):
    _name = 'test.pallet'
    _inherits = {'test.box': 'box_id'}
    _description = 'Test Pallet'

    box_id = fields.Many2one('test.box', 'Box', required=True,
                             ondelete='cascade')
    field_in_pallet = fields.Char('Field2')
class Pallet(models.Model):
    _name = 'test.pallet'
    _description = 'Test Pallet'

    box_id = fields.Many2one('test.box', 'Box', required=True,
                             ondelete='cascade',delegate=True)
    field_in_pallet = fields.Char('Field2')

And the second one: If I use _inherits in code, I cannot see there is any difference without it in my code. For example:

class Pallet(models.Model):
    _name = 'test.pallet'
    _inherits = {'test.box': 'box_id'}
    _description = 'Test Pallet'

    box_id = fields.Many2one('test.box', 'Box', required=True,
                             ondelete='cascade')
    field_in_pallet = fields.Char('Field2')
class Pallet(models.Model):
    _name = 'test.pallet'
    _description = 'Test Pallet'

    box_id = fields.Many2one('test.box', 'Box', required=True,
                             ondelete='cascade')
    field_in_pallet = fields.Char('Field2')

A sample Many2one field is enough.

1 Answers

For First question: These is a shortcut for the inheritance delegation. Instead of creating an _inherits dictionary, you can use the delegate=True attribute in the Many2one field definition. This will work exactly like the _inherits option. The main advantage is that this is simpler.

For Second Question: The first code, it create a new model (test.pallet) based on an existing one (test.box) and you can use the features it already has. So when you create a new record from test.pallet model it will create a record in test.box and the link between them is box_id.

in this case, you have inherited the test.box with all fields and you can show them in form, tree or other views without the need to recreate them in your model.

for second code: You are creating a new model from scratch without any inheriting.

In General: According to the official documentation, Odoo provides three types of inheritance:

• Class inheritance (extension): It is used to add new fields or methods to existing models.

• Prototype inheritance: It is used to copy the entire definition of the existing model. it is executed by using the _name and _inherit class attributes at the same time.

• Delegation inheritance: It is create a new model based on an existing one to use the features it already has. So it is copy a model's definitions without duplicating data structures uses the _inherits model attribute (note the additional s) or you can use the delegate=True attribute in the Many2one field definition without the need to use _inherits.

Related