当前位置:   article > 正文

sqlalchemy Annotated自定义Mapped类型_sqlalchemy mapped[datetime]

sqlalchemy mapped[datetime]

 Annotated 和 Mapped,这是 SQLAlchemy 2.0 引入的新特性,允许您使用 Python 类型注解来定义模型。

 

  1. from typing import Annotated
  2. from sqlalchemy.orm import Mapped
  3. from sqlalchemy.orm import mapped_column
  4. from sqlalchemy.orm import registry
  5. # typing tools will ignore init=False here
  6. intpk = Annotated[int, mapped_column(init=False, primary_key=True)]
  7. str50 = Annotated[str,mapped_column(String(50),nullable=True)]
  8. #定义创建时间字段,新增数据自动生成创建时间,与djingo models.DateField(auto_now_add=True)功能相同
  9. #default 和 default_factory:用于设置列的默认值。
  10. datetime_create = Annotated[DateTime,mapped_column(DateTime,nullable=False,default=datetime.now)]
  11. user_pk_id = Annotated[int ,mapped_column(ForeignKey('users.id'))]
  12. reg = registry()
  13. @reg.mapped_as_dataclass
  14. class User:
  15. __tablename__ = "user_account"
  16. id: Mapped[intpk]
  17. user_name :Mapped[str50]
  18. create_time :Mapped[datetime_create]
  19. @reg.mapped_as_dataclass
  20. class Userinfo:
  21. __tablename__ = "user_account"
  22. id: Mapped[intpk]
  23. user_pk :Mapped[user_pk_id]
  24. create_time :Mapped[datetime_create]
  25. @reg.mapped_as_dataclass
  26. class Userinfo:
  27. __tablename__ = "user_account"
  28. id: Mapped[intpk]
  29. user_pk :Mapped[user_pk_id]
  30. create_time :Mapped[datetime_create]
  31. # typing error: Argument missing for parameter "id"
  32. u1 = User()

  1. from decimal import Decimal
  2. from typing_extensions import Annotated
  3. from sqlalchemy import Numeric
  4. from sqlalchemy import String
  5. from sqlalchemy.orm import DeclarativeBase
  6. from sqlalchemy.orm import Mapped
  7. from sqlalchemy.orm import mapped_column
  8. from sqlalchemy.orm import registry
  9. str_30 = Annotated[str, 30]
  10. str_50 = Annotated[str, 50]
  11. num_12_4 = Annotated[Decimal, 12]
  12. num_6_2 = Annotated[Decimal, 6]
  13. class Base(DeclarativeBase):
  14. registry = registry(
  15. type_annotation_map={
  16. str_30: String(30),
  17. str_50: String(50),
  18. num_12_4: Numeric(12, 4),
  19. num_6_2: Numeric(6, 2),
  20. }
  21. )

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/521843
推荐阅读
相关标签
  

闽ICP备14008679号