31

I want to define a specific schema for a 'model' using flask-sqlalchemy. When you create a table object in sqlalchemy itself it has a parameter to pass for schema name.

How do I do this in flask-sqlalchemy?

3 Answers 3

71

When you define your model class use:

__table_args__ = {"schema":"schema_name"}

maybe it will save someone else some hunting.

Sign up to request clarification or add additional context in comments.

2 Comments

but is there any way to define schema in config file ?
Super helpful, and I believe this works b/c flask-sqlalchemy defers to sqlalchemy.orm under the hood. docs.sqlalchemy.org/en/14/orm/…
1

This is how I did it but I am also looking for a better way if possible -

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'}

Comments

-1

For future references:

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'
    ...

1 Comment

With the wink and all, this answer is still wrong. You're mixing databases and schemas. Binds provides a way to handle connections to different databases more or less transparently. A database contains one or more schemas. Some RDBMS such as MySQL do consider them equivalent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.