Skip to Content
Menu
This question has been flagged

I have this scenario: I have a new field in product.product and it's a Many2one field. The many2one field has a product_id column. Here's the sample code:


class MyMany2one():

​_name = "my.manytoone"


​name = fields.Char()

​product_id = fields.Many2one(

​comodel_name = "product.product"

​)



class ProductProduct():

​_inherit = "product.product"


​# in the product view, this will be a selection

​mymany2one = fields.Many2one(

​comodel_name = "my.manytoone"

​)


My issue is it does not populate the product_id in the many2one class after saving

Avatar
Discard
Best Answer

you can try this way:

class MyMany2one(models.Model):
_name = "my.manytoone"
name = fields.Char()
product_id = fields.Many2one(
comodel_name="product.product",
inverse_name="mymany2one",
)


class ProductProduct(models.Model):
_inherit = "product.product"

# In the product view, this will be a selection
mymany2one = fields.Many2one(
comodel_name="my.manytoone",
inverse_name="product_id",
)

By adding the inverse_name parameter to the product_id field in the my.manytoone class and the mymany2one field in the product.product class, you establish a two-way relationship between the two fields. This ensures that the product_id field in the my.manytoone class gets populated when a value is selected in the mymany2one field of product.product.

After making these modifications, update the module containing this code and restart the Odoo server. Then, when you create or edit a product.product record, select a value in the mymany2one field, and the corresponding product_id field in the my.manytoone class should populate correctly.

Avatar
Discard
Best Answer

Hi,

Am not sure about your design, if you need  product_id as Many2one inside your model, you have to write code for updating the product_id field inside your custom model.

Inherit the write method of product.product model, and if the mymany2one field has a value, update the product id into it.

But what if the same record is selected inside multiple products ?

Lets say, you have a record My Record 1 in your table and 2 products in products table P1 and P2, which value you will store inside the My Record 1 if for both P1 and P2, if user choose My Record 1 ?


If its possible to change it one2many field inside your model, you can achieve this without any extra coding. Remove many2one from your model and define a one2many field as follows:


product_ids = fields.One2many('product.product', 'mymany2one', string="Test")

Thanks

Avatar
Discard
Related Posts Replies Views Activity
3
Feb 25
35253
2
Aug 15
4846
2
Mar 15
4164
1
Jul 23
2338
1
May 23
2639