Public
Authored by OpenHazel

[Q] I want to easily create dynamic sqlalchemy model classes, based on other model classes. [Python] [SQLAlchemy]

Edited

I want to easily create dynamic sqlalchemy model classes, based on other model classes. With the new dynamic model classes using a different __tablename__ and be able to monkey patch relationship and foreignkey attributes. After some googling I came up with my own create_model_table_type function.

You can see a working gitlab snippet here.

What I want to know is how is this hack gonna bite me in the ass?

create_model_table_type_example.py 2.51 KB
  • The code is not problematic yet. I just googled long and hard to get it working.

    I inherit a class to be able to access all its inherited attributes. I change its __tablename__ and set it to __abstract__ to get around how sqlalchemy want to inherit classes. I also allow overriding attributes of the new class.

    I then copy all the __table__ columns from my src_table to my new dst_table and use the sqla mapper() function to change class attributes to use columns for the new dst_table.

    So there a lot of monkey patching. While in the tests Im running everything seems fine and I maybe want to later copy more then columns I still feel I might be missing something that is going to hurt real bad, sooner then later.

    So I need input.

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment