sqlalchemy是python做orm管理的非常重要的工具,sqlalchemy2.0版本relationship與上個版本有所不同,具體如下:
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import declarative_base SQLALCHEMY_DATABASE_URL='你的資料庫配置資訊' engine=create_engine(SQLALCHEMY_DATABASE_URL ,pool_pre_ping=True ) SessionLocal=sessionmaker( autoflush=False, bind=engine) Base=declarative_base() from typing import Optional,List from sqlalchemy import ForeignKey,SmallInteger,BigInteger,String,Text from sqlalchemy.orm import relationship,Mapped,mapped_column class TestTableInfo(Base): __tablename__='test_table_info' id:Mapped[int]=mapped_column(BigInteger,autoincrement=True,primary_key=True) num:Mapped[Optional[int]]=mapped_column(SmallInteger,default=None,comment='數字') schema_table:Mapped[str]=mapped_column(String(100),default=None,comment='表名') table_log_list:Mapped[List['TestTableLog']]=relationship(back_populates='test_table_info') class TestTableLog(Base): __tablename__='test_table_log' id:Mapped[int]=mapped_column(BigInteger,autoincrement=True,primary_key=True) table_id:Mapped[int]=mapped_column(BigInteger,ForeignKey('test_table_info.id'),key=True,comment='表id') result:Mapped[Optional[str]]=mapped_column(Text,default=None,comment='結果') test_table_info:Mapped['TestTableInfo']=relationship(back_populates='table_log_list')
TestTableInfo類和TestTableLog是一對多的關係,其中TestTableLog類中的table_id是外來鍵,關聯test_table_info表中的id。
兩個類中的relationship必須是一一對應的,table_log_list必須是TestTableLog中relationship的back_populates。同理,test_table_info也一樣。