代码之家  ›  专栏  ›  技术社区  ›  Chris R

如何在多个数据库和模式上重用sqlalchemyorm模型?

  •  1
  • Chris R  · 技术社区  · 14 年前

    Base = declarative_base()
    
    class Database(Base):
    
      __tablename__ = "databases"
      __table_args__ = (
        saschema.PrimaryKeyConstraint('db', 'role'),
        {
          'schema' : 'defines',
          },
        )
    
    
      db = Column(String, nullable=False)
      role = Column(String, nullable=False)
      server = Column(String)
    

    实际上,这个模型存在于多个数据库中,并且在这些数据库中它将以多个模式存在。对于任何一个手术,我只使用一个 (database, schema)

    现在,我可以使用以下命令设置数据库引擎:

    Session = scoped_session(sessionmaker())
    Session.configure(bind=my_db_engine)
    # ... do my operations on the model here.
    

    但我不知道怎么才能改变 __table_args__

    2 回复  |  直到 14 年前
        1
  •  1
  •   Nathan Villaescusa    14 年前

    一种选择是使用create_引擎将模型绑定到模式/数据库,而不是在实际的数据库中这样做。

    #first connect to the database that holds the DB and schema
    engine1 = create_engine('mysql://user:pass@db.com/schema1')
    
    Session = session(sessionmaker())
    session = Session(bind=engine1)
    
    #fetch the first database
    database = session.query(Database).first()
    
    engine2 = create_engine('mysql://user:pass@%s/%s' % (database.DB, database.schema))
    session2 = Session(bind=engine2)
    

    我不知道这是否理想,但这是一种方法。如果您提前缓存数据库列表,那么在大多数情况下,您只需创建一个会话。

        2
  •  1
  •   Community CDub    8 年前

    __abstract__ 有帮助。我提出了一个解决办法 here 那可能有用。它涉及到将具有特定架构/元数据的基添加到继承中。