I use Python and SQLAlchemy 2.0.23. My aim is to dynamically create SQLAlchemy models and tables in postgre database based on these models. I have several countries, and these are similar tables for all countries, so I use Dynamic Model class, to create a separate model for each country
from sqlalchemy import Column, DateTime, Float, BigInteger, String, Boolean, ForeignKey, Sequence
from sqlalchemy.ext.declarative import declared_attr, declarative_base
Base = declarative_base()
SCHEMA = 'schema'
class ModelBase(Base):
__abstract__ = True
__table_args__ = {'schema': SCHEMA}
class Model(ModelBase):
__abstract__ = True
id = Column(BigInteger, primary_key=True)
provider_id = Column(BigInteger)
card_bin = Column(String(10))
bank = Column(String(100))
card = Column(String(50))
card_type = Column(String(10))
class DynamicModel:
@staticmethod
def create(country_code: str):
class_name = f"model{country_code.upper()}"
table_name = f"model_table{country_code}"
id_seq = Sequence(f'{table_name}_id_seq', schema=SCHEMA)
class_attrs = {
'__tablename__': table_name,
'id': Column(BigInteger, id_seq, primary_key=True, server_default=id_seq.next_value()),
'provider_id': Column(BigInteger, ForeignKey(f'{SCHEMA}.provider__table_{country_code}.id'))
}
for key, value in Model.__dict__.items():
if isinstance(value, Column) and key not in class_attrs:
class_attrs[key] = value
return type(class_name, (Model,), class_attrs)
I cant owercome one problem – I want colums id and provider_id to be first in the created tables, as it is defined in Model class, but they allways are last ones in the table.
I tried varios solutions, but nothing helped to get columns in right order
Normunds is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.