pydantic:如何选择字段的类型?

Ale*_*ova 1 python python-3.x pydantic fastapi

我有一个 FastAPI 应用程序,我需要创建一个 Car 类,其中属性Wheelspeed可以采用 intstr 类型。怎么做?此代码不起作用,因为Wheelspeed将只有整数类型(第二次打印中不是 str ):

from pydantic import BaseModel


class Car(BaseModel):
    wheel: int | str
    speed: int | str


bmw = Car(wheel=4, speed=250)
mercedes = Car(wheel='4', speed='200')

print(type(bmw.wheel), type(bmw.speed))
print(type(mercedes.wheel), type(mercedes.speed))
Run Code Online (Sandbox Code Playgroud)

结果是:

<class 'int'> <class 'int'>
<class 'int'> <class 'int'>
Run Code Online (Sandbox Code Playgroud)

jua*_*aga 5

所以,我个人会在这里使用pydantic.StrictIntand pydantic.StricStr(实际上,我几乎在任何地方都使用它们,特别StrictStr是因为几乎任何对象都可以被强制为字符串):

import pydantic


class Car(pydantic.BaseModel):
    wheel: pydantic.StrictInt | pydantic.StrictStr
    speed: pydantic.StrictInt | pydantic.StrictStr


bmw = Car(wheel=4, speed=250)
mercedes = Car(wheel='4', speed='200')

print(type(bmw.wheel), type(bmw.speed))
print(type(mercedes.wheel), type(mercedes.speed))
Run Code Online (Sandbox Code Playgroud)

这打印:

<class 'int'> <class 'int'>
<class 'str'> <class 'str'>
Run Code Online (Sandbox Code Playgroud)