The different "openerp model inheritance" mechanisms: what's the difference between them, and when should they be used ?
2 答案
This is a wide question:
In OpenERP we have many main type of inheritance:
Classical using Python inheritance.
It allows to add specific "generic" behavior to Model by inheriting classes that derive from orm.Model like geoModel that adds goegraphic support.
class Myclass(GeoModel, AUtilsClass):
Standard Using _inherit
The main objective is to add new behaviors/extend existing models. For example you want to add a new field to an invoice and add a new method: `
class AccountInvoice(orm.Model):
_inherit = "account.invoice"
_column = {'my_field': fields.char('My new field')}
def a_new_func(self, cr, uid, ids, x, y, context=None):
# my stuff
return something
`
You can also override existing methods:`
def existing(self, cr, uid, ids, x, y, z, context=None):
parent_res = super(AccountInvoice, self).existing(cr, uid, ids, x, y, z, context=context)
# my stuff
return parent_res_plus_my_stuff`
It is important to note that the order of the super call is defined by the inheritance graph of the addons (the depends key in __openerp__.py
).
It is important to notice that _inherit
can be a string or a list. You can do _inherit = ['model_1', 'model_2']
.
List allows to create a class that concatenate multiple Model
, TransientModel
or better AbstractModel
into a single new model.
So what about our '_name' property
- If the _name as the same value as the inherited class it will do a basic inheritance.
- If you forget to add the
_inherit
you will redefine the model - If your class _inherit one model and you set a
_name
different it will create a new model in a new database table. - If your class inherit many model you have to set
_name
if your override an existing model this way you may have some trouble, it should be avoided. It is better to use this to create new classes that inherit from abstract model.
Polymorphic data using _inherits
When using _inherits
you will do a kind of polymorphic model in the database way.
For example product.product
inherits product.template
or res.users
inherits res.partner
. This mean we create a model that gets the know how of a Model but adds aditional data/columns in a new database table. So when you create a user, all partner data is stored in res_partner table (and a partner is created) and all user related info is stored in res_users table.
To do this we use a dict:
_inherits = {'res.partner': 'partner_id'}
The key corresponds to the base model and the value to the foreign key to the base model.
From here you can mix inheritance if you dare...
Hope it helps.
here is step by step guide about odoo inheritance: https://learnopenerp.blogspot.com/2018/01/inheritance-in-models-and-views.html