首页 > 解决方案 > Python pydantic 范围验证

问题描述

我有下一个模型:

class UserPreference(BaseModel):
    smoking: Optional[int] = Field(..., ge=0, le=4, description="How mach user = smoking", example=2)
    alcohol: Optional[int] = Field(..., ge=0, le=4, description="How mach user = alcohol", example=2)
    kids: Optional[int] = Field(..., ge=0, le=4, description="How many kids user has", example=2)
    height: Optional[int] = Field(..., ge=50, le=250, description="Height of the user", example=180)
    weight: Optional[int] = Field(..., ge=20, le=200, description="weight of the user", example=80)
    sport: Optional[int] = Field(..., ge=0, le=4, description="How mach user = sport", example=2)

    class Config:
        orm_mode = True

我想从上面的类创建一个新类。每个字段必须是 2 个项目的列表(上方字段的低边界和高边界)

一个粗略的解决方案:

class UserSearchPreference(BaseModel):
    low_smoking: Optional[int] = Field(..., ge=0, le=4, description="How mach user = smoking", example=2)
    high_smoking: Optional[int] = Field(..., ge=0, le=4, description="How mach user = smoking", example=2)
    low_alcohol: Optional[int] = Field(..., ge=0, le=4, description="How mach user = alcohol", example=2)
    high_alcohol: Optional[int] = Field(..., ge=0, le=4, description="How mach user = alcohol", example=2)
    low_kids: Optional[int] = Field(..., ge=0, le=4, description="How many kids user has", example=2)
    high_kids: Optional[int] = Field(..., ge=0, le=4, description="How many kids user has", example=2)
    low_height: Optional[int] = Field(..., ge=50, le=250, description="Height of the user", example=180)
    high_height: Optional[int] = Field(..., ge=50, le=250, description="Height of the user", example=180)
    low_weight: Optional[int] = Field(..., ge=20, le=200, description="weight of the user", example=80)
    high_weight: Optional[int] = Field(..., ge=20, le=200, description="weight of the user", example=80)
    low_sport: Optional[int] = Field(..., ge=0, le=4, description="How mach user = sport", example=2)
    high_sport: Optional[int] = Field(..., ge=0, le=4, description="How mach user = sport", example=2)

我该如何实施?

PS 另外,最好检查一下low_boundary < high_boundary( list[0] < list[-1])

标签: pythonpydantic

解决方案


推荐阅读