How to override the main create method in odoo11?

1.1k views Asked by At

I have a lot of models (around 30) that overrides the create method to check for a license state and all of them go like this:

class Model1(models.Model):
    _name='testing_model1'

    @api.model
    def create(self)
        check_license(self)
        return super(Model1, self).create(values)

Is there any way to add the "check_license" function in the main create so I don't have to write it in every model?

2

There are 2 answers

4
CZoellner On BEST ANSWER

I see two easy possibilities:

1. Usage of Odoo's inheritance

Odoo's inheritance mechanism is also working on the base model. The following example is from Odoo V13 module base_import, but in Odoo V11 there are some examples, too (e.g. in web):

class Base(models.AbstractModel):
    _inherit = 'base'

    @api.model
    def get_import_templates(self):
        """
        Get the import templates label and path.

        :return: a list(dict) containing label and template path
                 like ``[{'label': 'foo', 'template': 'path'}]``
        """
        return []

Following is the code which you'll need (won't work in later versions because create has changed):

class Base(models.AbstractModel):
    _inherit = 'base'

    def create(self, values):
        """
        Extended core method to implement a license check,
        before creating a record.
        """
        check_license(self)
        return super().create(values)

2. Using a mixin (lot of examples in Odoo code)

It's possible to use a mixin class to restrict the license check to some models, which will inherit this mixin. The 1. concept isn't restricting it (but it is possible there too).

class LicenseCheckMixin(models.AbstractModel):
    _name = 'license.check.mixin'

    def create(self, values):
        """
        Extended create method to implement a license check,
        before creating a record.
        """
        check_license(self)
        return super().create(values)

You can then inherit this mixin in other Odoo models:

class SaleOrder(models.Model):
    _name = 'sale.order'
    _inherit = ['sale.order', 'license.check.mixin']
2
Charif DZ On

You can do that by munkey patching but I really don't recommend to do this, and what you should do is create a small module that do this and make sure that all other modules depends on it, this way the call to check will be done only one time.

Peace of advice when you repeat a code in two module consider extracting it to a small module and make sure the two modules depends on it.

Like in your case you can create module check_license put all related code to this operation in it fix dependency on the others 30 modules this will make sure when you install one of those modules the new module will be installed first, and the main benefits is the call to check for license will happen only one time even if you install all 30 modules