class flask_sqlalchemy.SQLAlchemy(app=None, use_native_unicode=True, session_options=None, metadata=None, query_class=<class 'flask_sqlalchemy.BaseQuery'>, model_class=<class 'flask_sqlalchemy.model.Model'>, engine_options=None)

This class is used to control the SQLAlchemy integration to one or more Flask applications. Depending on how you initialize the object it is usable right away or will attach as needed to a Flask application.

There are two usage modes which work very similarly. One is binding the instance to a very specific Flask application:

app = Flask(__name__)
db = SQLAlchemy(app)

The second possibility is to create the object once and configure the application later to support it:

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    return app

The difference between the two is that in the first case methods like create_all() and drop_all() will work all the time but in the second case a flask.Flask.app_context() has to exist.

By default Flask-SQLAlchemy will apply some backend-specific settings to improve your experience with them.

As of SQLAlchemy 0.6 SQLAlchemy will probe the library for native unicode support. If it detects unicode it will let the library handle that, otherwise do that itself. Sometimes this detection can fail in which case you might want to set use_native_unicode (or the SQLALCHEMY_NATIVE_UNICODE configuration key) to False. Note that the configuration key overrides the value you pass to the constructor. Direct support for use_native_unicode and SQLALCHEMY_NATIVE_UNICODE are deprecated as of v2.4 and will be removed in v3.0. engine_options and SQLALCHEMY_ENGINE_OPTIONS may be used instead.

This class also provides access to all the SQLAlchemy functions and classes from the sqlalchemy and sqlalchemy.orm modules. So you can declare models like this:

class User(db.Model):
    username = db.Column(db.String(80), unique=True)
    pw_hash = db.Column(db.String(80))

You can still use sqlalchemy and sqlalchemy.orm directly, but note that Flask-SQLAlchemy customizations are available only through an instance of this SQLAlchemy class. Query classes default to BaseQuery for db.Query, db.Model.query_class, and the default query_class for db.relationship and db.backref. If you use these interfaces through sqlalchemy and sqlalchemy.orm directly, the default query class will be that of sqlalchemy.

Check types carefully

Don’t perform type or isinstance checks against db.Table, which emulates Table behavior but is not a class. db.Table exposes the Table interface, but is a function which allows omission of metadata.

The session_options parameter, if provided, is a dict of parameters to be passed to the session constructor. See Session for the standard options.

The engine_options parameter, if provided, is a dict of parameters to be passed to create engine. See create_engine() for the standard options. The values given here will be merged with and override anything set in the 'SQLALCHEMY_ENGINE_OPTIONS' config variable or othewise set by this library.

New in version 0.10: The session_options parameter was added.

New in version 0.16: scopefunc is now accepted on session_options. It allows specifying a custom function which will define the SQLAlchemy session’s scoping.

New in version 2.1: The metadata parameter was added. This allows for setting custom naming conventions among other, non-trivial things.

The query_class parameter was added, to allow customisation of the query class, in place of the default of BaseQuery.

The model_class parameter was added, which allows a custom model class to be used in place of Model.

Changed in version 2.1: Utilise the same query class across session, Model.query and Query.

New in version 2.4: The engine_options parameter was added.

Changed in version 2.4: The use_native_unicode parameter was deprecated.

Changed in version 2.4.3: COMMIT_ON_TEARDOWN is deprecated and will be removed in version 3.1. Call db.session.commit() directly instead.

Query = None

Default query class used by Model.query and other queries. Customize this by passing query_class to SQLAlchemy(). Defaults to BaseQuery.

apply_driver_hacks(app, sa_url, options)

This method is called before engine creation and used to inject driver specific hacks into the options. The options parameter is a dictionary of keyword arguments that will then be used to call the sqlalchemy.create_engine() function.

The default implementation provides some saner defaults for things like pool sizes for MySQL and sqlite. Also it injects the setting of SQLALCHEMY_NATIVE_UNICODE.

Changed in version 2.5: Returns (sa_url, options). SQLAlchemy 1.4 made the URL immutable, so any changes to it must now be passed back up to the original caller.

apply_pool_defaults(app, options)

Changed in version 2.5: Returns the options dict, for consistency with apply_driver_hacks().

create_all(bind='__all__', app=None)

Creates all tables.

Changed in version 0.12: Parameters were added

create_engine(sa_url, engine_opts)

Override this method to have final say over how the SQLAlchemy engine is created.

In most cases, you will want to use 'SQLALCHEMY_ENGINE_OPTIONS' config variable or set engine_options for SQLAlchemy().


Create a scoped_session on the factory from create_session().

An extra key 'scopefunc' can be set on the options dict to specify a custom scope function. If it’s not provided, Flask’s app context stack identity is used. This will ensure that sessions are created and removed with the request/response cycle, and should be fine in most cases.


options – dict of keyword arguments passed to session class in create_session


Create the session factory used by create_scoped_session().

The factory must return an object that SQLAlchemy recognizes as a session, or registering session events may raise an exception.

Valid factories include a Session class or a sessionmaker.

The default implementation creates a sessionmaker for SignallingSession.


options – dict of keyword arguments passed to session class

drop_all(bind='__all__', app=None)

Drops all tables.

Changed in version 0.12: Parameters were added

property engine

Gives access to the engine. If the database configuration is bound to a specific application (initialized with an application) this will always return a database connection. If however the current application is used this might raise a RuntimeError if no application is active at the moment.


Helper method that implements the logic to look up an application.


Returns a dictionary with a table->engine mapping.

This is suitable for use of sessionmaker(binds=db.get_binds(app)).

get_engine(app=None, bind=None)

Returns a specific engine.


Returns a list of all tables relevant for a bind.


This callback can be used to initialize an application for the use with this database setup. Never use a database in the context of an application not initialized that way or connections will leak.

make_connector(app=None, bind=None)

Creates the connector for a given state and bind.

make_declarative_base(model, metadata=None)

Creates the declarative base that all models will inherit from.

  • model – base model class (or a tuple of base classes) to pass to declarative_base(). Or a class returned from declarative_base, in which case a new base class is not created.

  • metadataMetaData instance to use, or none to use SQLAlchemy’s default.

property metadata

The metadata associated with db.Model.

reflect(bind='__all__', app=None)

Reflects tables from the database.

Changed in version 0.12: Parameters were added


class flask_sqlalchemy.Model

Base class for SQLAlchemy declarative base model.

To define models, subclass db.Model, not this class. To customize db.Model, subclass this and pass it as model_class to SQLAlchemy.


Optionally declares the bind to use. None refers to the default bind. For more information see Multiple Databases with Binds.


The name of the table in the database. This is required by SQLAlchemy; however, Flask-SQLAlchemy will set it automatically if a model has a primary key defined. If the __table__ or __tablename__ is set explicitly, that will be used instead.

class flask_sqlalchemy.BaseQuery(entities: Sequence[_ColumnsClauseArgument[Any]], session: Session | None = None)

SQLAlchemy Query subclass with convenience methods for querying in a web application.

This is the default query object used for models, and exposed as Query. Override the query class for an individual model by subclassing this and setting query_class.


Like first() but aborts with 404 if not found instead of returning None.

get_or_404(ident, description=None)

Like get() but aborts with 404 if not found instead of returning None.

paginate(page=None, per_page=None, error_out=True, max_per_page=None)

Returns per_page items from page page.

If page or per_page are None, they will be retrieved from the request query. If max_per_page is specified, per_page will be limited to that value. If there is no request or they aren’t in the query, they default to 1 and 20 respectively.

When error_out is True (default), the following rules will cause a 404 response:

  • No items are found and page is not 1.

  • page is less than 1, or per_page is negative.

  • page or per_page are not ints.

When error_out is False, page and per_page default to 1 and 20 respectively.

Returns a Pagination object.


class flask_sqlalchemy.SignallingSession(db, autocommit=False, autoflush=True, **options)

The signalling session is the default session that Flask-SQLAlchemy uses. It extends the default session system with bind selection and modification tracking.

If you want to use a different session you can override the SQLAlchemy.create_session() function.

New in version 2.0.

New in version 2.1: The binds option was added, which allows a session to be joined to an external transaction.

get_bind(mapper=None, clause=None)

Return the engine or connection for a given model or table, using the __bind_key__ if it is set.


class flask_sqlalchemy.Pagination(query, page, per_page, total, items)

Internal helper class returned by BaseQuery.paginate(). You can also construct it from any other SQLAlchemy query object if you are working with other libraries. Additionally it is possible to pass None as query object in which case the prev() and next() will no longer work.

property has_next

True if a next page exists.

property has_prev

True if a previous page exists


the items for the current page

iter_pages(left_edge=2, left_current=2, right_current=5, right_edge=2)

Iterates over the page numbers in the pagination. The four parameters control the thresholds how many numbers should be produced from the sides. Skipped page numbers are represented as None. This is how you could render such a pagination in the templates:

{% macro render_pagination(pagination, endpoint) %}
  <div class=pagination>
  {%- for page in pagination.iter_pages() %}
    {% if page %}
      {% if page != pagination.page %}
        <a href="{{ url_for(endpoint, page=page) }}">{{ page }}</a>
      {% else %}
        <strong>{{ page }}</strong>
      {% endif %}
    {% else %}
      <span class=ellipsis></span>
    {% endif %}
  {%- endfor %}
{% endmacro %}

Returns a Pagination object for the next page.

property next_num

Number of the next page


the current page number (1 indexed)

property pages

The total number of pages


the number of items to be displayed on a page.


Returns a Pagination object for the previous page.

property prev_num

Number of the previous page.


the unlimited query object that was used to create this pagination object.


the total number of items matching the query


In debug mode Flask-SQLAlchemy will log all the SQL queries sent to the database. This information is available until the end of request which makes it possible to easily ensure that the SQL generated is the one expected on errors or in unittesting. If you don’t want to enable the DEBUG mode for your unittests you can also enable the query recording by setting the 'SQLALCHEMY_RECORD_QUERIES' config variable to True. This is automatically enabled if Flask is in testing mode.

The value returned will be a list of named tuples with the following attributes:


The SQL statement issued


The parameters for the SQL statement

start_time / end_time

Time the query started / the results arrived. Please keep in mind that the timer function used depends on your platform. These values are only useful for sorting or comparing. They do not necessarily represent an absolute timestamp.


Time the query took in seconds


A string giving a rough estimation of where in your application query was issued. The exact format is undefined so don’t try to reconstruct filename or function name.