Annotated
和 Mapped
,这是 SQLAlchemy 2.0 引入的新特性,允许您使用 Python 类型注解来定义模型。
from typing import Annotated
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import registry
# typing tools will ignore init=False here
intpk = Annotated[int, mapped_column(init=False, primary_key=True)]
str50 = Annotated[str,mapped_column(String(50),nullable=True)]
#定义创建时间字段,新增数据自动生成创建时间,与djingo models.DateField(auto_now_add=True)功能相同
#default 和 default_factory:用于设置列的默认值。
datetime_create = Annotated[DateTime,mapped_column(DateTime,nullable=False,default=datetime.now)]
user_pk_id = Annotated[int ,mapped_column(ForeignKey('users.id'))]
reg = registry()
@reg.mapped_as_dataclass
class User:
__tablename__ = "user_account"
id: Mapped[intpk]
user_name :Mapped[str50]
create_time :Mapped[datetime_create]
@reg.mapped_as_dataclass
class Userinfo:
__tablename__ = "user_account"
id: Mapped[intpk]
user_pk :Mapped[user_pk_id]
create_time :Mapped[datetime_create]
@reg.mapped_as_dataclass
class Userinfo:
__tablename__ = "user_account"
id: Mapped[intpk]
user_pk :Mapped[user_pk_id]
create_time :Mapped[datetime_create]
# typing error: Argument missing for parameter "id"
u1 = User()
from decimal import Decimal
from typing_extensions import Annotated
from sqlalchemy import Numeric
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import registry
str_30 = Annotated[str, 30]
str_50 = Annotated[str, 50]
num_12_4 = Annotated[Decimal, 12]
num_6_2 = Annotated[Decimal, 6]
class Base(DeclarativeBase):
registry = registry(
type_annotation_map={
str_30: String(30),
str_50: String(50),
num_12_4: Numeric(12, 4),
num_6_2: Numeric(6, 2),
}
)