Odooers论坛

欢迎!

该社区面向专业人士和我们产品和服务的爱好者。
分享和讨论最好的内容和新的营销理念,建立您的专业形象,一起成为更好的营销人员。


0

Upgrade custom module, convert Many2one field into Many2many field

3 注释
形象
丢弃
形象
odoo
-

Why would you want to change from a many2one to a many2many though?You're most likely better off to create a one2many that links to a many2one - it'll behave the same as a many2many but it has benefits. On a many2many you cannot filter by default and if you export the data you won't get everything out automatically. With a one2many you can. Just a tip. :-)

形象
odoo
-

@Yenthe Your approach it's helpful, I've not even though, so, can I take your answer as If I can change the field from Many2one to One2many or Many2many and the data persist?

形象
odoo
-

I can't use the One2many field because 1 a.object can have N b.object and 1 b.object can be in N a.object, so I should use the Many2many field, but I need to know if the information persists after changing the field type from one2Many to (Many2many or One2many).

1 答案
0
形象
odoo
最佳答案

I did it this way:

first I created a new field type Many2many:

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

then a function that gets the value of the old Many2one field:

@api.model
    def _fill_objects(self):
        products = self.env['module.name'].search(
            ['&', ('objectA_id', '!=', False), ('objectA_ids', '=', False)])
        for r in products:
            if not r.objectA_ids and r.objectA_id:
                r.objectA_ids = [(4, r.objectA_id.id)]
            else:
                r.objectA_ids = False


and in the last step, i did make an XML call to the function when the module it's installing:


<odoo>
   <data noupdate="1">
    <function model="module.name" name="_fill_objects"/>
  </data>
</odoo>


after installing the module the new field has the values of the old field, there's no way for change the field type without lost data, so we have to create a new field, copy data from the old field, and make the old field invisible on view.


<odoo>
  <data>
    <record id="view_module_name_adjustment" model="ir.ui.view">
      <field name="name">module.name.view.form</field>
      <field name="model">module.name</field>
      <field name="inherit_id" ref="module_view_external_id"/>
      <field name="arch" type="xml">
        <field name="objectA_id" position="after">
          <field name="objectA_ids" widget="many2many_tags"/>
        </field>
        <field name="objectA_id" position="attributes">
          <attribute name="invisible">True</attribute>
        </field>
      </field>
    </record>
   </data>
</odoo>
形象
丢弃