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?
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']