python - 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]
)
解决方案
推荐阅读
- discord.js - 获取公会中的每个频道
- javascript - javascript:合并具有相同主密钥的对象
- python - 分词的时间复杂度分析
- angular - 为什么我的 Angular CLI 创建 CSS 而不是 SCSS 文件?
- android - 我的 android studio 中不建议使用 Dagger 组件并导致我构建错误?
- mongodb - 猫鼬:填充没有任何 ObjectId 的猫鼬
- python - 如何打开 unicode 编码的 URL?
- html - HTML 标记
- mongodb - MongoDb:将日期字符串转换为 mongodb 3.6 中的特定格式
- common-lisp - 描述方法的特殊行为,由 Sonya E. Keene 解释