我有一个用 Pydantic 2 编写的电路,用于验证提交的字段:
from pydantic import BaseModel
class CommandSchema(BaseModel):
product: int
title: str
如何检查发送的产品字段是否是产品模型中的键?这个想法是使用类似以下代码的内容:
class CommandSchema(BaseModel):
product: int
title: str
@validator('product')
def validate_product_field(cls, value):
session = Session(bind=engine)
if session.query(Product).filter(Product.id == value).first():
return value
raise ValueError(f"Field '{value}' already not exists in the database.")
但我使用异步连接数据库。因此,我不能等待这样的代码:
async with engine.begin() as conn:
async_session = sessionmaker(conn, class_=AsyncSession, expire_on_commit=False)
async with async_session() as session:
if await session.execute(Product.select().where(Product.id == value)):
return value
raise ValueError(f"Field '{value}' already not exists in the database.")
因为它将在非异步方法内启动