Skip to Content
Menu
This question has been flagged
1 Reply
8222 Views

Dear all,

I am doing a code review of some of our custom modules and found the following models which habe a many2One relation from both models. 
Could you please explain me if this can be correct, and if so what logic behind this is? I assumed the models are linked with each other if I add a relation filed on one side.

class product_template(models.Model):
_inherit="product.template"
handling_group_id = fields.Many2one('handling.group', string='Handling Group')

class HandlingGroup(models.Model):
    _name='handling.group'
    _rec_name = 'handle_grp'
    name = fields.Char(required=True)
    product_id = fields.Many2one("product.product", string="Product ID")


Next I found was a relation on the one model as Many2Many and on the other as Many2One relation. 

class product_template(models.Model):
_inherit="product.template"
    branding_ids = fields.Many2many('branding.item', 'branding_item_rel', 'product_id', 'brand_id', string="Branding Items")


class BrandingPosition(models.Model):
    _name = 'branding.position'
    _description = 'Branding'
    _order = "name"
    product_id = fields.Many2one('product.product', string="SKU", required=True)


Hope you can explain to me what the sense of this is. And why I would implement it like this.
Thanks in advance!

 

Avatar
Discard

You must learn odoo customization: https://plus.google.com/collection/MrdEWE

Best Answer

Hi,

In your code, you can see handling.group has relation with product.product not with product.template and 

It is not compulsory to add many2one in both models when you want to establish a relationship with 2 models.

You can use only one many2one field to use that model data in another model.

In a simple way,

To use Many2one you only need to define comodel name parameter in a field:

customer_id = fields.Many2one('res.partner')


To use One2many you need to define comodel name with inverse field name:

for ex:- To add custom model One2many record in res.partner:

Class Partner(models.Model):

    _inherit = 'res.partner'

    my_model_ids = fields.One2many('my.model', 'partner_id')


Class Mymode(models.Model):

        _name = 'my.model'

        partner_id = fields.Many2one('res.partner')

For many2many :


Class Mymode(models.Model):

        _name = 'my.model'

        partner_ids = fields.Many2many('res.partner')     

You can add optional name of the column referring to "these" in the table ``relation

To get more details about using these fields you can refer the comment details available in the file : 

odoo > fields.py

Class Many2one

Class One2many

Class Many2many

To get examples you can see documentation of Odoo:

https://www.odoo.com/documentation/12.0/howtos/backend.html#relational-fields



Avatar
Discard
Related Posts Replies Views Activity
1
Mar 23
786
0
Dec 22
1514
0
Jun 21
1843
0
Jun 20
4179
1
Nov 19
1742