FastAPI与Pydantic验证器对其他模型的组合



我有一些Pydantic对象,我试图使用__init__来更新字段(例如时间)或发送事件,但每次我从FastAPI处理程序返回Pydantic对象时,事件都被调用。

class OtherModel(BaseModel):
value: int

class SomeModel(BaseModel):
other: OtherModel
@validator('other', pre=True, always=True)
def are_items_in_order(cls, other):
cur_val = 0
if cur_val > other.value:
raise ValueError('out of order')
return other

def some_function() -> SomeModel:
val1 = OtherModel(value=1)
something = SomeModel(other=val1)
print(something)
return something

@app.get("/test", response_model=SomeModel)
async def exec_test():
something = some_function()
print(something)
return something

第一次打印的输出看起来不错

other=OtherModel(value=1)
other=OtherModel(value=1)

但是我从Pydantic得到一个错误,因为它试图执行我的验证器,但现在用dict代替对象

if cur_val > other.value:
AttributeError: 'dict' object has no attribute 'value'

如何处理或避免此失败?

似乎您希望单独验证每个列表值(将其与0进行比较),那么each_item=True验证器应该可以为您工作