| 1 |
Advanced Customization |
| 2 |
====================== |
| 3 |
|
| 4 |
The various objects managed by the extension can be customized by passing arguments to |
| 5 |
the :class:`.SQLAlchemy` constructor. |
| 6 |
|
| 7 |
|
| 8 |
Model Class |
| 9 |
----------- |
| 10 |
|
| 11 |
SQLAlchemy models all inherit from a declarative base class. This is exposed as |
| 12 |
``db.Model`` in Flask-SQLAlchemy, which all models extend. This can be customized by |
| 13 |
subclassing the default and passing the custom class to ``model_class``. |
| 14 |
|
| 15 |
The following example gives every model an integer primary key, or a foreign key for |
| 16 |
joined-table inheritance. |
| 17 |
|
| 18 |
.. note:: |
| 19 |
Integer primary keys for everything is not necessarily the best database design |
| 20 |
(that's up to your project's requirements), this is only an example. |
| 21 |
|
| 22 |
.. code-block:: python |
| 23 |
|
| 24 |
from sqlalchemy import Integer, String, ForeignKey |
| 25 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, declared_attr |
| 26 |
|
| 27 |
class Base(DeclarativeBase): |
| 28 |
@declared_attr.cascading |
| 29 |
@classmethod |
| 30 |
def id(cls): |
| 31 |
for base in cls.__mro__[1:-1]: |
| 32 |
if getattr(base, "__table__", None) is not None: |
| 33 |
return mapped_column(ForeignKey(base.id), primary_key=True) |
| 34 |
else: |
| 35 |
return mapped_column(Integer, primary_key=True) |
| 36 |
|
| 37 |
db = SQLAlchemy(app, model_class=Base) |
| 38 |
|
| 39 |
class User(db.Model): |
| 40 |
name: Mapped[str] = mapped_column(String) |
| 41 |
|
| 42 |
class Employee(User): |
| 43 |
title: Mapped[str] = mapped_column(String) |
| 44 |
|
| 45 |
|
| 46 |
Abstract Models and Mixins |
| 47 |
-------------------------- |
| 48 |
|
| 49 |
If behavior is only needed on some models rather than all models, use an abstract model |
| 50 |
base class to customize only those models. For example, if some models should track when |
| 51 |
they are created or updated. |
| 52 |
|
| 53 |
.. code-block:: python |
| 54 |
|
| 55 |
from datetime import datetime |
| 56 |
from sqlalchemy import DateTime, Integer, String |
| 57 |
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, declared_attr |
| 58 |
|
| 59 |
class TimestampModel(db.Model): |
| 60 |
__abstract__ = True |
| 61 |
created: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow) |
| 62 |
updated: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) |
| 63 |
|
| 64 |
class Author(db.Model): |
| 65 |
id: Mapped[int] = mapped_column(Integer, primary_key=True) |
| 66 |
username: Mapped[str] = mapped_column(String, unique=True, nullable=False) |
| 67 |
|
| 68 |
class Post(TimestampModel): |
| 69 |
id: Mapped[int] = mapped_column(Integer, primary_key=True) |
| 70 |
title: Mapped[str] = mapped_column(String, nullable=False) |
| 71 |
|
| 72 |
This can also be done with a mixin class, inheriting from ``db.Model`` separately. |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
|
| 76 |
class TimestampMixin: |
| 77 |
created: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.utcnow) |
| 78 |
updated: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) |
| 79 |
|
| 80 |
class Post(TimestampMixin, db.Model): |
| 81 |
id: Mapped[int] = mapped_column(Integer, primary_key=True) |
| 82 |
title: Mapped[str] = mapped_column(String, nullable=False) |
| 83 |
|
| 84 |
|
| 85 |
Disabling Table Name Generation |
| 86 |
------------------------------- |
| 87 |
|
| 88 |
Some projects prefer to set each model's ``__tablename__`` manually rather than relying |
| 89 |
on Flask-SQLAlchemy's detection and generation. The simple way to achieve that is to |
| 90 |
set each ``__tablename__`` and not modify the base class. However, the table name |
| 91 |
generation can be disabled by setting `disable_autonaming=True` in the `SQLAlchemy` constructor. |
| 92 |
|
| 93 |
.. code-block:: python |
| 94 |
|
| 95 |
class Base(sa_orm.DeclarativeBase): |
| 96 |
pass |
| 97 |
|
| 98 |
db = SQLAlchemy(app, model_class=Base, disable_autonaming=True) |
| 99 |
|
| 100 |
|
| 101 |
Session Class |
| 102 |
------------- |
| 103 |
|
| 104 |
Flask-SQLAlchemy's :class:`.Session` class chooses which engine to query based on the |
| 105 |
bind key associated with the model or table. However, there are other strategies such as |
| 106 |
horizontal sharding that can be implemented with a different session class. The |
| 107 |
``class_`` key to the ``session_options`` argument to the extension to change the |
| 108 |
session class. |
| 109 |
|
| 110 |
Flask-SQLAlchemy will always pass the extension instance as the ``db`` argument to the |
| 111 |
session, so it must accept that to continue working. That can be used to get access to |
| 112 |
``db.engines``. |
| 113 |
|
| 114 |
.. code-block:: python |
| 115 |
|
| 116 |
from sqlalchemy.ext.horizontal_shard import ShardedSession |
| 117 |
from flask_sqlalchemy.session import Session |
| 118 |
|
| 119 |
class CustomSession(ShardedSession, Session): |
| 120 |
... |
| 121 |
|
| 122 |
db = SQLAlchemy(session_options={"class_": CustomSession}) |
| 123 |
|
| 124 |
|
| 125 |
Query Class |
| 126 |
----------- |
| 127 |
|
| 128 |
.. warning:: |
| 129 |
The query interface is considered legacy in SQLAlchemy. This includes |
| 130 |
``session.query``, ``Model.query``, ``db.Query``, and ``lazy="dynamic"`` |
| 131 |
relationships. Prefer using ``session.execute(select(...))`` instead. |
| 132 |
|
| 133 |
It is possible to customize the query interface used by the session, models, and |
| 134 |
relationships. This can be used to add extra query methods. For example, you could add |
| 135 |
a ``get_or`` method that gets a row or returns a default. |
| 136 |
|
| 137 |
.. code-block:: python |
| 138 |
|
| 139 |
from flask_sqlalchemy.query import Query |
| 140 |
|
| 141 |
class GetOrQuery(Query): |
| 142 |
def get_or(self, ident, default=None): |
| 143 |
out = self.get(ident) |
| 144 |
|
| 145 |
if out is None: |
| 146 |
return default |
| 147 |
|
| 148 |
return out |
| 149 |
|
| 150 |
db = SQLAlchemy(query_class=GetOrQuery) |
| 151 |
|
| 152 |
user = User.query.get_or(user_id, anonymous_user) |
| 153 |
|
| 154 |
Passing the ``query_class`` argument will customize ``db.Query``, ``db.session.query``, |
| 155 |
``Model.query``, and ``db.relationship(lazy="dynamic")`` relationships. It's also |
| 156 |
possible to customize these on a per-object basis. |
| 157 |
|
| 158 |
To customize a specific model's ``query`` property, set the ``query_class`` attribute on |
| 159 |
the model class. |
| 160 |
|
| 161 |
.. code-block:: python |
| 162 |
|
| 163 |
class User(db.Model): |
| 164 |
query_class = GetOrQuery |
| 165 |
|
| 166 |
To customize a specific dynamic relationship, pass the ``query_class`` argument to the |
| 167 |
relationship. |
| 168 |
|
| 169 |
.. code-block:: python |
| 170 |
|
| 171 |
db.relationship(User, lazy="dynamic", query_class=GetOrQuery) |
| 172 |
|
| 173 |
To customize only ``session.query``, pass the ``query_cls`` key to the |
| 174 |
``session_options`` argument to the constructor. |
| 175 |
|
| 176 |
.. code-block:: python |
| 177 |
|
| 178 |
db = SQLAlchemy(session_options={"query_cls": GetOrQuery}) |