The database I'm currently working with has some information split into multiple columns as the interface used to have multiple inputs for each line. The plan is to merge them into one column, with the data of the old columns joined by newlines.
Here's an example:
class Foo(db.model):
info1 = CharField(default="")
info2 = CharField(default="")
info3 = CharField(default="")
Which should become:
class Foo(db.model):
info = TextField(default="")
Where the data in the new info
column should be info1 + "\n" + info2 + "\n" + info3
.
A basic start, to my knowledge:
info_field = TextField(default="")
migrate(
migrator.add_column("foo", "info", info_field),
)
migrate(
migrator.drop_column("foo", "info1"),
migrator.drop_column("foo", "info2"),
migrator.drop_column("foo", "info3"),
)
And somehow in between the two calls make the merge.
Is this possible with a SQL query or should I iterate over the foo
objects in the database and do a "\n".join([info1, info2, info3])
for example?
In between you can just write an UPDATE query:
db.execute_sql("""
update "foo" set "info" = "a" || '\n' || "b" || '\n' || "c"
""")
You can get more fancy and add the new field to the model and do it that way, if you prefer:
Foo._meta.add_field('info', info_field)
Foo.update(info=Foo.a + '\n' + Foo.b + '\n' + Foo.c).execute()