如何解决未引发 IntegrityError 外键违规
使用下面的代码和以下序列,我怀疑存在外键违规的 IntegrityError。不幸的是,错误没有出现。
- 创建
Customer(id=1)
- 创建
Booking(cid=1)
- 删除
Customer(id=1)
#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
# schemas.py
from pydantic import BaseModel
class Customer(BaseModel):
name:str
type:str
class ShowCustomer(Customer):
id:int
class Config():
orm_mode = True
class Booking(BaseModel):
name:str
type:str
class ShowBooking(Booking):
id:int
cid:int
class Config():
orm_mode = True
#models.py
from sqlalchemy import Column,Integer,String,ForeignKey
from sqlalchemy.orm import relationship
from database import Base
class Customer(Base):
__tablename__ = "customers"
id = Column(Integer,primary_key=True,index=True)
name = Column(String)
type = Column(String)
booking = relationship("Booking",back_populates="customer")
class Booking(Base):
__tablename__ = "bookings"
id = Column(Integer,index=True)
cid = Column(Integer,ForeignKey("customers.id"),nullable=False)
name = Column(String)
type = Column(String)
customer = relationship('Customer',back_populates="booking")
#database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
sqlALCHEMY_DATABASE_URL = 'sqlite:///./cloud2.db'
engine = create_engine(sqlALCHEMY_DATABASE_URL,connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(bind=engine,autocommit=False,autoflush=False)
Base = declarative_base()
def get_db():
db=SessionLocal()
try:
yield db
finally:
db.close()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。