Skip to Content
Menu
This question has been flagged
785 Zobrazenia

Odoo is able to customize easily according to our requirements.For this we  need to modify the behavior of existing models or methods to suit specific business requirements. Instead of changing the core code , Odoo allows us to override models and methods using its powerful object-relational mapping (ORM) framework.

In this blog, we’ll walk through:

  • How to override a model
  • How to override a method (standard and computed)

How to Override a Model

To override a model, you must inherit it in a custom module.

from odoo import models, fields

class ResPartner(models.Model):
    _inherit = 'res.partner'  # Inheriting existing model

    x_custom_field = fields.Char(string="Custom Field")

It will add the new field x_custom_field in already existing model res.partner


How to Override a Method

You can override:

  • Regular methods (e.g., create, write, unlink)
  • Compute methods
  • Button or action methods

Overriding the create method:

from odoo import models, fields, api


class ResPartner(models.Model):

    _inherit = 'res.partner'


    @api.model

    def create(self, vals):

        vals['name'] = vals.get('name', '').upper()  # Convert name to uppercase

        return super(ResPartner, self).create(vals)


Overriding a Compute Method

If a field uses @api.depends, you can override its compute method

from odoo import models, fields, api


class SaleOrder(models.Model):

    _inherit = 'sale.order'


    custom_total = fields.Float(string="Custom Total", compute="_compute_custom_total")


    @api.depends('order_line')

    def _compute_custom_total(self):

        for record in self:

            record.custom_total = sum(line.price_total for line in record.order_line)


For clear code we can follow these steps:

Always use super() when overriding core methods to maintain original functionality unless you fully replace it.

Avoid direct database changes. Use ORM methods (create, write, unlink).

Add module dependencies in __manifest__.py if you inherit models from them.

Test thoroughly, especially if overriding sensitive methods like create, write, or unlink.



Avatar
Zrušiť

For the sake of it - the res.partner inherit of the create() method is actually incorrect.
The decorator of that method should be @api.model_create_multi since create() in res.partner expects a list of dictionaries rather than just a dictionary.

class ResPartner(models.Model):
_inherit = 'res.partner'
@api.model_create_multi
def create(self, vals_list):
# do something before creating contacts
partner_ids = super().create(vals_list)
# do something after creating contacts / with the created contacts
return partner_ids

Related Posts Replies Zobrazenia Aktivita
2
jún 15
3776
2
dec 23
9745
2
júl 23
2593
1
apr 22
5715
1
feb 16
5213