Skip to content

[ADD] util.convert_many2one_field_to_many2many #306

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions src/util/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def make_index_name(table_name, column_name):
alter_column_type,
column_exists,
column_type,
create_m2m,
explode_execute,
explode_query_range,
format_query,
Expand All @@ -60,6 +61,7 @@ def make_index_name(table_name, column_name):
pg_text2html,
remove_column,
table_exists,
target_of,
)
from .records import _remove_import_export_paths
from .report import add_to_migration_reports, get_anchor_link_to_record
Expand Down Expand Up @@ -731,6 +733,49 @@ def convert_field_to_html(cr, model, field, skip_inherit=()):
convert_field_to_html(cr, inh.model, field, skip_inherit=skip_inherit)


def convert_many2one_field_to_many2many(cr, model, field, new_name=None, m2m_table=None, col1=None, col2=None):
_validate_model(model)
if new_name is None:
if not field.endswith("_id"):
raise ValueError("Please specify the new name explicitly")
new_name = field + "s"

table1 = table_of_model(cr, model)
table2, _, _ = target_of(cr, table1, field)

if m2m_table is None:
m2m_table = "{}_{}_rel".format(*sorted([table1, table2]))

if col1 is None:
col1 = "{}_id".format(table1)
if col2 is None:
col2 = "{}_id".format(table2)

create_m2m(cr, m2m_table, table1, table2, col1, col2)

fill_query = format_query(
cr,
"""
INSERT INTO {m2m}({col1}, {col2})
SELECT id, {field}
FROM {table}
WHERE {field} IS NOT NULL
""",
m2m=m2m_table,
col1=col1,
col2=col2,
field=field,
table=table1,
)
cr.execute(fill_query)
remove_column(cr, table1, field)
rename_field(cr, model, field, new_name)


# Because we can.
m2o2m2m = convert_many2one_field_to_many2many


def _convert_field_to_company_dependent(
cr, model, field, type, target_model=None, default_value=None, default_value_ref=None, company_field="company_id"
):
Expand Down