连接数据库
sqlalchemy
库
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 声明地址
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
# 声明引擎
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
# 声明会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 建立客户端
Base = declarative_base()
ORM
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
is_active = Column(Boolean, default=True)
items = relationship("Item", back_populates="owner")
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)
owner_id = Column(Integer, ForeignKey("users.id"))
owner = relationship("User", back_populates="items")
当访问中的属性items时User(如中的)my_user.items
,它将具有一个ItemSQLAlchemy模型列表(来自items表),该模型具有指向users表中该记录的外键。
当您访问时my_user.items,SQLAlchemy实际上会从items表中的数据库中获取项目,并在此处填充它们。
并且当访问中的属性owner时Item,它将包含表中的UserSQLAlchemy模型users。它将使用owner_id属性/列及其外键来了解要从users表中获取哪个记录。