Pydantic:如何为领域选择类型的选择?
我有一个FastApi应用程序,需要创建一个汽车类,其中属性 wheel 和 speed 可以采用INT 或 str类型。怎么做?此代码不起作用,因为 wheel 和 speed 将只有一个整数类型(不是第二次打印中的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))
结果是:
<class 'int'> <class 'int'>
<class 'int'> <class 'int'>
I have a FastAPI app and I need to create a Car class in which the attributes wheel and speed can take an int or str type. How to do it? This code does not work, because wheel and speed will have only an integer type (not str in second print):
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))
Result is:
<class 'int'> <class 'int'>
<class 'int'> <class 'int'>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,我个人会亲自使用
pydantic.strictint
和pydantic.stricstr
在此处(实际上,我几乎在任何地方都使用这些,尤其是stricts strictstr
,因为实际上任何对象都可以胁迫到字符串):此打印:
So, I would personally just use
pydantic.StrictInt
andpydantic.StricStr
here (and actually, I use those almost everywhere, particularlyStrictStr
because practically any object can be coerced to a string):This prints:
类型规范中有顺序。使用
int | str
,该值将被视为int
,否则str
。逆转顺序str | int
将导致值将其视为str
,否则int
。反向订单的问题在于,几乎所有内容都可以视为str
,因此bmw
值将被施加到str
。示例:这里的关键是您需要选择哪种类型优先。
There is order in the type specification. With
int | str
, the value will be treated as anint
if possible, otherwise astr
. Reversing the orderstr | int
will result in the values being treated asstr
if possible, otherwiseint
. The problem with reversing the order is that pretty much everything can be treated as astr
so thebmw
values will be cast tostr
. Example:The key here is that you need to choose which type takes precedence.
您正在寻找的是键入的联合选项。一个示例在下面
,而不是简单的str或int,您可以在pydantic中为这些类型编写自己的类,并根据需要添加更多属性。
What you are looking for is the Union option from typing. An example is below
Further, instead of simple str or int you can write your own classes for those types in pydantic and add more attributes as needed.