flask-sqlalchemy - PostgreSQL - 为表定义特定的模式?

时间:2012-08-08 22:11:36

标签: python flask flask-sqlalchemy

我想为一个'模型定义一个特定的架构。使用flask-sqlalchemy。在sqlalchemy中创建表对象时,它有一个参数可以传递模式名称。

我如何在flask-sqlalchemy中执行此操作?

3 个答案:

答案 0 :(得分:40)

定义模型类时使用:

__table_args__ = {"schema":"schema_name"}
也许它会拯救别人一些狩猎。

答案 1 :(得分:2)

供将来参考:

db = flask.ext.sqlalchemy.SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'your_default_schema_db_uri'
app.config['SQLALCHEMY_BINDS'] = {'other_schema': 'your_other_db_uri'}

class TableA(db.Model):
    # This belongs to Default schema, it doesn't need specify __bind_key__
    ...

class TableB(db.Model):
      # This belongs to other_schema
    __bind_key__ = 'other_schema'
    ...

答案 2 :(得分:0)

这就是我的做法,但我也在寻找更好的方法-

db = flask.ext.sqlalchemy.SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'your_default_schema_db_uri'

class Entity():
    __table_args__ = {
        'schema': 'schema_name'
    }
    # common columns below

class TableA(Entity, db.Model):
    # This belongs to Default schema, it doesn't need specify __bind_key__
    __table_args__ = {'schema' : Entity.__table_args__["schema"], 
                      'comment': 'TableA'}

class TableB(Entity, db.Model):
      # This belongs to other_schema
    __table_args__ = {'schema' : Entity.__table_args__["schema"], 
                      'comment': 'TableA'}