【问题标题】:How do I *dynamically* set the schema in SQLAlchemy for MSSQL?我如何*动态*在 SQLAlchemy 中为 MSSQL 设置模式?
【发布时间】:2021-11-09 15:39:16
【问题描述】:

this question 我学会了如何在 ORM 定义上设置架构:

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)

但我现在需要使架构可配置。我尝试在创建对象时传递 table_args 参数,但它仍在尝试我在类定义中放置的架构。

【问题讨论】:

    标签: python sql-server sqlalchemy database-schema pymssql


    【解决方案1】:

    目前我发现的更好的解决方案是创建一个返回类的函数:

    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
        
    

    然后,使用它

    Notification = get_notification_class('animal')
    
    obj = Notification('1', 'doggy')
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 2017-08-10
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      相关资源
      最近更新 更多