sqlalchemy Annotated自定义Mapped类型

 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),
        }
    )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值