Python 未引发IntegrityError外键冲突
使用下面的代码和下面的序列,我怀疑一个IntegrityError违反了外键。不幸的是,没有引发错误Python 未引发IntegrityError外键冲突,python,sqlite,sqlalchemy,foreign-keys,Python,Sqlite,Sqlalchemy,Foreign Keys,使用下面的代码和下面的序列,我怀疑一个IntegrityError违反了外键。不幸的是,没有引发错误 创建客户(id=1) 创建预订(cid=1) 删除客户(id=1) #schemas.py 从pydantic导入BaseModel 类别客户(基本型号): 姓名:str 类型:str 类别ShowCustomer(客户): id:int 类配置(): orm_模式=真 课堂预订(基本模式): 姓名:str 类型:str 课堂展示预订(预订): id:int cid:int 类配置(): o
- 创建
客户(id=1)
- 创建
预订(cid=1)
- 删除
客户(id=1)
#schemas.py
从pydantic导入BaseModel
类别客户(基本型号):
姓名:str
类型:str
类别ShowCustomer(客户):
id:int
类配置():
orm_模式=真
课堂预订(基本模式):
姓名:str
类型:str
课堂展示预订(预订):
id:int
cid:int
类配置():
orm_模式=真
#models.py
从sqlalchemy导入列、整数、字符串、外键
从sqlalchemy.orm导入关系
从数据库导入库
类别客户(基本):
__tablename_=“客户”
id=列(整数,主键=True,索引=True)
名称=列(字符串)
类型=列(字符串)
预订=关系(“预订”,back_populates=“客户”)
订舱(基本):
__tablename=“预订”
id=列(整数,主键=True,索引=True)
cid=列(整数,ForeignKey(“customers.id”),nullable=False)
名称=列(字符串)
类型=列(字符串)
客户=关系(“客户”,背面填充=“预订”)
#database.py
从sqlalchemy导入创建引擎
从sqlalchemy.orm导入sessionmaker
从sqlalchemy.ext.declarative导入声明性基础
SQLALCHEMY\u数据库\u URL='0sqlite:///./cloud2.db'
engine=create_engine(SQLALCHEMY_数据库_URL,connect_args={“check_same_thread”:False})
SessionLocal=sessionmaker(bind=engine,autocommit=False,autoflush=False)
Base=声明性_Base()
def get_db():
db=会话本地()
尝试:
收益率分贝
最后:
db.close()
Related:在上面的代码中,即使我不首先创建客户也可以创建预订,我们需要强制执行外键。上面的链接帮助了我
#main.py
from typing import List
from fastapi.params import Depends
from schemas import Customer, ShowCustomer, Booking, ShowBooking
from fastapi import FastAPI, HTTPException
from database import get_db, engine, Base
from sqlalchemy.orm import Session
import models
models.Base.metadata.create_all(engine)
app = FastAPI()
@app.post("/customer")
async def customer(req: Customer, db: Session=Depends(get_db)):
new_customer=models.Customer(name=req.name, type=req.type)
db.add(new_customer)
db.commit()
db.refresh(new_customer)
return new_customer
@app.get("/customer", response_model=List[ShowCustomer])
async def create(db: Session=Depends(get_db)):
customers=db.query(models.Customer).all()
return customers
@app.delete('/customer/{id}')
def destory(id, db: Session=Depends(get_db)):
customer=db.query(models.Customer).filter(models.Customer.id == id)
if not customer.first():
raise HTTPException(status_code=404,
detail=f'Blog with the id {id} is not available '
)
customer.delete(synchronize_session=False)
db.commit()
return 'done'
@app.post("/booking")
async def read_root(req: Booking, db: Session=Depends(get_db)):
new_booking=models.Booking(name=req.name, type=req.type, cid=1)
db.add(new_booking)
db.commit()
db.refresh(new_booking)
return new_booking
@app.get("/booking",response_model=List[ShowBooking])
async def read_root(db: Session=Depends(get_db)):
bookings=db.query(models.Booking).all()
return bookings