Skip to content

Commit a2db216

Browse files
committed
Update abstract models and mixins
1 parent 1d877e8 commit a2db216

File tree

1 file changed

+12
-17
lines changed

1 file changed

+12
-17
lines changed

docs/customizing.rst

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -59,25 +59,28 @@ they are created or updated.
5959
6060
class TimestampModel(db.Model):
6161
__abstract__ = True
62-
created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
63-
updated = db.Column(db.DateTime, onupdate=datetime.utcnow)
62+
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=datetime.utcnow)
63+
updated: Mapped[datetime] = mapped_column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
6464
6565
class Author(db.Model):
66-
...
66+
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
67+
username: Mapped[str] = mapped_column(db.String, unique=True, nullable=False)
6768
6869
class Post(TimestampModel):
69-
...
70+
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
71+
title: Mapped[str] = mapped_column(db.String, nullable=False)
7072
7173
This can also be done with a mixin class, inheriting from ``db.Model`` separately.
7274

7375
.. code-block:: python
7476
75-
class TimestampMixin:
76-
created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
77-
updated = db.Column(db.DateTime, onupdate=datetime.utcnow)
77+
class TimestampModel:
78+
created: Mapped[datetime] = mapped_column(db.DateTime, nullable=False, default=datetime.utcnow)
79+
updated: Mapped[datetime] = mapped_column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
7880
79-
class Post(TimestampMixin, db.Model):
80-
...
81+
class Post2(TimestampModel, db.Model):
82+
id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
83+
title: Mapped[str] = mapped_column(db.String, nullable=False)
8184
8285
8386
Session Class
@@ -168,14 +171,6 @@ on Flask-SQLAlchemy's detection and generation. The simple way to achieve that i
168171
set each ``__tablename__`` and not modify the base class. However, the table name
169172
generation can be disabled by setting `disable_autonaming=True` in the `SQLAlchemy` constructor.
170173

171-
Example code using the SQLAlchemy 1.x (legacy) API:
172-
173-
.. code-block:: python
174-
175-
db = SQLAlchemy(app, disable_autonaming=True)
176-
177-
Example code using the SQLAlchemy 2.x declarative base:
178-
179174
.. code-block:: python
180175
181176
class Base(sa_orm.DeclarativeBase):

0 commit comments

Comments
 (0)