[Python开发笔记] SQLAlchemy 实体类示例与元数据访问

76 阅读1分钟

SQLAlchemy 实体类示例与元数据访问笔记(python操作)

实体类示例

from sqlalchemy import Integer, String, Float
from sqlalchemy.orm import Mapped, mapped_column

class UserEntity:
    __tablename__ = "user"
    
    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    name: Mapped[str] = mapped_column(String(50), nullable=False)
    age: Mapped[int] = mapped_column(Integer, default=0)
    score: Mapped[float] = mapped_column(Float, nullable=True)

元数据访问

表信息访问
# 获取表对象
table = UserEntity.__table__
# 获取表名
table_name = UserEntity.__table__.name
列信息访问
# 获取所有的列
columns = UserEntity.__table__.columns

# 遍历实体类的数据库字段
for column in columns:
  print(f"column_name: {column.name}")