pydantic fields

02. Fields

Field 函数用于自定义字段,为其添加元数据

默认值 default

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from pydantic import BaseModel, Field


class User(BaseModel):
    name: str = Field(default='John Doe')


user = User()
print(user)
#> name='John Doe'

还可以使用 default_factory 定义一个可变的默认值

1
2
3
4
5
6
7
from uuid import uuid4

from pydantic import BaseModel, Field


class User(BaseModel):
    id: str = Field(default_factory=lambda: uuid4().hex)

If you use typing.Optional, it doesn’t mean that the field has a default value of None!

Annotated 合用

Field 可以写进 Annotated 哦(不过有啥用嘛)

1
2
3
4
5
6
7
8
9
from uuid import uuid4

from typing_extensions import Annotated

from pydantic import BaseModel, Field


class User(BaseModel):
    id: Annotated[str, Field(default_factory=lambda: uuid4().hex)]

default_factory 只能写在 Annotated 里面,而 default 无法写在里面,只能直接在外面通过赋值的形式写

字段别名 alias

有三种方法定义一个 alias:

  • Field(..., alias='foo')
  • Field(..., validation_alias='foo')
  • Field(..., serialization_alias='foo')

alias 在验证序列化时都被用到,除非用第二、三种方法分别开来

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from pydantic import BaseModel, Field


class User(BaseModel):
    name: str = Field(..., alias='username')


user = User(username='johndoe')  
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True))  
#> {'username': 'johndoe'}

by_alias=True 一定要显式地写出来!默认是 False

If you want to use an alias only for validation, you can use the validation_alias parameter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from pydantic import BaseModel, Field


class User(BaseModel):
    name: str = Field(..., validation_alias='username')


user = User(username='johndoe')  
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True))  
#> {'name': 'johndoe'}

If you only want to define an alias for serialization, you can use the serialization_alias parameter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from pydantic import BaseModel, Field


class User(BaseModel):
    name: str = Field(..., serialization_alias='username')


user = User(name='johndoe')  
print(user)
#> name='johndoe'
print(user.model_dump(by_alias=True))  
#> {'username': 'johndoe'}

数字条件约束

可以用以下参数来限制数字型字段的值:

  • gt - greater than
  • lt - less than
  • ge - greater than or equal to
  • le - less than or equal to
  • multiple_of - a multiple of the given number 给定数字的倍数
  • allow_inf_nan - allow 'inf''-inf''nan' values
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from pydantic import BaseModel, Field


class Foo(BaseModel):
    positive: int = Field(gt=0)
    non_negative: int = Field(ge=0)
    negative: int = Field(lt=0)
    non_positive: int = Field(le=0)
    even: int = Field(multiple_of=2)
    love_for_pydantic: float = Field(allow_inf_nan=True)


foo = Foo(
    positive=1,
    non_negative=0,
    negative=-1,
    non_positive=0,
    even=2,
    love_for_pydantic=float('inf'),
)
print(foo)
"""
positive=1 non_negative=0 negative=-1 non_positive=0 even=2 love_for_pydantic=inf
"""

对那些混合类型来说,使用数字约束可能会出错。使用 Annotated 来避免这种情况

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from typing import Optional

from typing_extensions import Annotated

from pydantic import BaseModel, Field


class Foo(BaseModel):
    positive: Optional[Annotated[int, Field(gt=0)]]
    # Can error in some cases, not recommended:
    non_negative: Optional[int] = Field(ge=0)