cerhovice
cerhovice

Reputation: 686

How to migrate Python models to new models?

I don't know much about Python, but I just started working at a company that uses Python for its main CMS. They gave me the assignment of moving the company from their old product, to their new product. The old product had a custom ORM built on top of SQLAlchemy. The old product had models such as:

user
business
client

The new product also has a custom ORM built on top of SQLAlchemy. The new product also has models such as:

user
business
client

However, the fields in these models are completely different.

They have spent 2 years building the new product, a major upgrade of the old product, and now they want to import all the data from the old product into the new product.

I need to do 2 things:

  1. Pull data from old product database and serialize the objects
  2. Deserialize the objects and put it in the new product database

Here is my confusion:

When I am in the new system, and I deserialize the objects from the old system, I will have a model that thinks its name is "user" or "business" yet it will have fields that don't match the "user" or "business" models that exist in the new system.

I am thinking that this can be solved with namespacing? How do I mark the old "user" objects as "old system"?

Upvotes: 0

Views: 169

Answers (1)

van
van

Reputation: 76992

Assuming the models are defined in different packages(or modules or even libraries), just use import with aliases in order to handle the same model names:

# file: migration.py

from myoldcrm.models import User as UserOLD
from myoldcrm import Session as SessionOLD

from mynewcrm.models import User
from mynewcrm import Session

def migrate_users():
    users = SessionOLD.query(UserOLD).all()
    for user in users:
        ser = user.serialize() # or any other way you have to do this
        des = User.deserialize(ser) # deserialize using new model class
        Session.add(des)
    Session.commit()

Upvotes: 1

Related Questions