0

On this question I learned how to set the schema on an ORM definition:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Notification(Base):
    __tablename__ = "dog"
    __table_args__ = {"schema": "animal"}
    id = Column(Integer, primary_key=True)
    name = Column(String)

But I now need to make the schema configurable. I have tried passing the table_args parameter at object creation, but it's still trying the schema I put on the class definition.

Flamma
  • 258
  • 4
  • 15

1 Answers1

0

The better solution I have found so far is to create a function that returns the class:

function get_notification_class(schema: str):

    class Notification(Base):
        __tablename__ = "dog"
        __table_args__ = {"schema": schema}
        id = Column(Integer, primary_key=True)
        name = Column(String)

    return Notification
    

And then, to use it

Notification = get_notification_class('animal')

obj = Notification('1', 'doggy')
Flamma
  • 258
  • 4
  • 15