@@ -37,10 +37,10 @@ joined-table inheritance.
37
37
db = SQLAlchemy(app, model_class = Base)
38
38
39
39
class User (db .Model ):
40
- name: Mapped[str ] = mapped_column(String)
40
+ name: Mapped[str ]
41
41
42
42
class Employee (User ):
43
- title: Mapped[str ] = mapped_column(String)
43
+ title: Mapped[str ]
44
44
45
45
46
46
Abstract Models and Mixins
@@ -52,34 +52,33 @@ they are created or updated.
52
52
53
53
.. code-block :: python
54
54
55
- from datetime import datetime
56
- from sqlalchemy import DateTime, Integer, String
57
- from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, declared_attr
55
+ from datetime import datetime, timezone
56
+ from sqlalchemy.orm import Mapped, mapped_column
58
57
59
58
class TimestampModel (db .Model ):
60
59
__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 )
60
+ created: Mapped[datetime] = mapped_column(default = lambda : datetime.now(timezone.utc) )
61
+ updated: Mapped[datetime] = mapped_column(default = lambda : datetime.now(timezone.utc) , onupdate = lambda : datetime.now(timezone.utc) )
63
62
64
63
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 )
64
+ id : Mapped[int ] = mapped_column(primary_key = True )
65
+ username: Mapped[str ] = mapped_column(unique = True )
67
66
68
67
class Post (TimestampModel ):
69
- id : Mapped[int ] = mapped_column(Integer, primary_key = True )
70
- title: Mapped[str ] = mapped_column(String, nullable = False )
68
+ id : Mapped[int ] = mapped_column(primary_key = True )
69
+ title: Mapped[str ]
71
70
72
71
This can also be done with a mixin class, inheriting from ``db.Model `` separately.
73
72
74
73
.. code-block :: python
75
74
76
75
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 )
76
+ created: Mapped[datetime] = mapped_column(default = lambda : datetime.now(timezone.utc) )
77
+ updated: Mapped[datetime] = mapped_column(default = lambda : datetime.now(timezone.utc) , onupdate = lambda : datetime.now(timezone.utc) )
79
78
80
79
class Post (TimestampMixin , db .Model ):
81
- id : Mapped[int ] = mapped_column(Integer, primary_key = True )
82
- title: Mapped[str ] = mapped_column(String, nullable = False )
80
+ id : Mapped[int ] = mapped_column(primary_key = True )
81
+ title: Mapped[str ]
83
82
84
83
85
84
Disabling Table Name Generation
0 commit comments