| 1 |
Models and Tables |
| 2 |
================= |
| 3 |
|
| 4 |
Use the ``db.Model`` class to define models, or the ``db.Table`` class to create tables. |
| 5 |
Both handle Flask-SQLAlchemy's bind keys to associate with a specific engine. |
| 6 |
|
| 7 |
Initializing the Base Class |
| 8 |
--------------------------- |
| 9 |
|
| 10 |
``SQLAlchemy`` 2.x offers several possible base classes for your models: |
| 11 |
`DeclarativeBase`_ or `DeclarativeBaseNoMeta`_. |
| 12 |
|
| 13 |
Create a subclass of one of those classes: |
| 14 |
|
| 15 |
.. code-block:: python |
| 16 |
|
| 17 |
from flask import Flask |
| 18 |
from flask_sqlalchemy import SQLAlchemy |
| 19 |
from sqlalchemy.orm import DeclarativeBase |
| 20 |
|
| 21 |
class Base(DeclarativeBase): |
| 22 |
pass |
| 23 |
|
| 24 |
.. _DeclarativeBase: https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.DeclarativeBase |
| 25 |
.. _DeclarativeBaseNoMeta: https://docs.sqlalchemy.org/en/20/orm/mapping_api.html#sqlalchemy.orm.DeclarativeBaseNoMeta |
| 26 |
|
| 27 |
If desired, you can enable `SQLAlchemy's native support for data classes`_ |
| 28 |
by adding `MappedAsDataclass` as an additional parent class. |
| 29 |
|
| 30 |
.. code-block:: python |
| 31 |
|
| 32 |
from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass |
| 33 |
|
| 34 |
class Base(DeclarativeBase, MappedAsDataclass): |
| 35 |
pass |
| 36 |
|
| 37 |
.. _SQLAlchemy's native support for data classes: https://docs.sqlalchemy.org/en/20/changelog/whatsnew_20.html#native-support-for-dataclasses-mapped-as-orm-models |
| 38 |
|
| 39 |
|
| 40 |
You can optionally construct the :class:`.SQLAlchemy` object with a custom |
| 41 |
:class:`~sqlalchemy.schema.MetaData` object. This allows you to specify a custom |
| 42 |
constraint `naming convention`_. This makes constraint names consistent and predictable, |
| 43 |
useful when using migrations, as described by `Alembic`_. |
| 44 |
|
| 45 |
.. code-block:: python |
| 46 |
|
| 47 |
from sqlalchemy import MetaData |
| 48 |
|
| 49 |
class Base(DeclarativeBase): |
| 50 |
metadata = MetaData(naming_convention={ |
| 51 |
"ix": 'ix_%(column_0_label)s', |
| 52 |
"uq": "uq_%(table_name)s_%(column_0_name)s", |
| 53 |
"ck": "ck_%(table_name)s_%(constraint_name)s", |
| 54 |
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", |
| 55 |
"pk": "pk_%(table_name)s" |
| 56 |
}) |
| 57 |
|
| 58 |
.. _naming convention: https://docs.sqlalchemy.org/core/constraints.html#constraint-naming-conventions |
| 59 |
.. _Alembic: https://alembic.sqlalchemy.org/en/latest/naming.html |
| 60 |
|
| 61 |
|
| 62 |
Initialize the Extension |
| 63 |
------------------------ |
| 64 |
|
| 65 |
Once you've defined a base class, create the ``db`` object using the ``SQLAlchemy`` constructor. |
| 66 |
|
| 67 |
.. code-block:: python |
| 68 |
|
| 69 |
db = SQLAlchemy(model_class=Base) |
| 70 |
|
| 71 |
|
| 72 |
Defining Models |
| 73 |
--------------- |
| 74 |
|
| 75 |
See SQLAlchemy's `declarative documentation`_ for full information about defining model |
| 76 |
classes declaratively. |
| 77 |
|
| 78 |
.. _declarative documentation: https://docs.sqlalchemy.org/en/20/orm/declarative_tables.html |
| 79 |
|
| 80 |
Subclass ``db.Model`` to create a model class. Unlike plain SQLAlchemy, |
| 81 |
Flask-SQLAlchemy's model will automatically generate a table name if ``__tablename__`` |
| 82 |
is not set and a primary key column is defined. |
| 83 |
|
| 84 |
.. code-block:: python |
| 85 |
|
| 86 |
from sqlalchemy.orm import Mapped, mapped_column |
| 87 |
|
| 88 |
class User(db.Model): |
| 89 |
id: Mapped[int] = mapped_column(db.Integer, primary_key=True) |
| 90 |
username: Mapped[str] = mapped_column(db.String, unique=True, nullable=False) |
| 91 |
email: Mapped[str] = mapped_column(db.String) |
| 92 |
|
| 93 |
|
| 94 |
Defining a model does not create it in the database. Use :meth:`~.SQLAlchemy.create_all` |
| 95 |
to create the models and tables after defining them. If you define models in submodules, |
| 96 |
you must import them so that SQLAlchemy knows about them before calling ``create_all``. |
| 97 |
|
| 98 |
.. code-block:: python |
| 99 |
|
| 100 |
with app.app_context(): |
| 101 |
db.create_all() |
| 102 |
|
| 103 |
|
| 104 |
Defining Tables |
| 105 |
--------------- |
| 106 |
|
| 107 |
See SQLAlchemy's `table documentation`_ for full information about defining table |
| 108 |
objects. |
| 109 |
|
| 110 |
.. _table documentation: https://docs.sqlalchemy.org/en/20/core/metadata.html |
| 111 |
|
| 112 |
Create instances of ``db.Table`` to define tables. The class takes a table name, then |
| 113 |
any columns and other table parts such as columns and constraints. Unlike plain |
| 114 |
SQLAlchemy, the ``metadata`` argument is not required. A metadata will be chosen based |
| 115 |
on the ``bind_key`` argument, or the default will be used. |
| 116 |
|
| 117 |
A common reason to create a table directly is when defining many to many relationships. |
| 118 |
The association table doesn't need its own model class, as it will be accessed through |
| 119 |
the relevant relationship attributes on the related models. |
| 120 |
|
| 121 |
.. code-block:: python |
| 122 |
|
| 123 |
import sqlalchemy as sa |
| 124 |
|
| 125 |
user_book_m2m = db.Table( |
| 126 |
"user_book", |
| 127 |
sa.Column("user_id", sa.ForeignKey(User.id), primary_key=True), |
| 128 |
sa.Column("book_id", sa.ForeignKey(Book.id), primary_key=True), |
| 129 |
) |
| 130 |
|
| 131 |
|
| 132 |
Reflecting Tables |
| 133 |
----------------- |
| 134 |
|
| 135 |
If you are connecting to a database that already has tables, SQLAlchemy can detect that |
| 136 |
schema and create tables with columns automatically. This is called reflection. Those |
| 137 |
tables can also be assigned to model classes with the ``__table__`` attribute instead of |
| 138 |
defining the full model. |
| 139 |
|
| 140 |
Call the :meth:`~.SQLAlchemy.reflect` method on the extension. It will reflect all the |
| 141 |
tables for each bind key. Each metadata's ``tables`` attribute will contain the detected |
| 142 |
table objects. |
| 143 |
|
| 144 |
.. code-block:: python |
| 145 |
|
| 146 |
with app.app_context(): |
| 147 |
db.reflect() |
| 148 |
|
| 149 |
class User: |
| 150 |
__table__ = db.metadatas["auth"].tables["user"] |
| 151 |
|
| 152 |
In most cases, it will be more maintainable to define the model classes yourself. You |
| 153 |
only need to define the models and columns you will actually use, even if you're |
| 154 |
connecting to a broader schema. IDEs will know the available attributes, and migration |
| 155 |
tools like Alembic can detect changes and generate schema migrations. |