Skip to content

Commit

Permalink
updating docs with more JSON Schema info (#8171)
Browse files Browse the repository at this point in the history
Co-authored-by: psychedelicious <4822129+psychedelicious@users.noreply.github.com>
Co-authored-by: Marcelo Trylesinski <marcelotryle@gmail.com>
  • Loading branch information
3 people committed Nov 27, 2023
1 parent 7f03cfc commit 22e6444
Show file tree
Hide file tree
Showing 5 changed files with 695 additions and 260 deletions.
88 changes: 38 additions & 50 deletions docs/concepts/fields.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
??? api "API Documentation"
[`pydantic.fields.Field`][pydantic.fields.Field]<br>

The `Field` function is used to customize and add metadata to fields of models.
The [`Field`][pydantic.fields.Field] function is used to customize and add metadata to fields of models.

## Default values

Expand Down Expand Up @@ -40,7 +40,7 @@ class User(BaseModel):

## Using `Annotated`

The `Field` function can also be used together with `Annotated`.
The [`Field`][pydantic.fields.Field] function can also be used together with [`Annotated`][annotated].

```py
from uuid import uuid4
Expand All @@ -54,6 +54,11 @@ class User(BaseModel):
id: Annotated[str, Field(default_factory=lambda: uuid4().hex)]
```

!!! note
Defaults can be set outside [`Annotated`][annotated] as the assigned value or with `Field.default_factory` inside
[`Annotated`][annotated]. The `Field.default` argument is not supported inside [`Annotated`][annotated].


## Field aliases

For validation and serialization, you can define an alias for a field.
Expand Down Expand Up @@ -679,7 +684,7 @@ See the [Discriminated Unions] docs for more details.

## Strict Mode

The `strict` parameter on a `Field` specifies whether the field should be validated in "strict mode".
The `strict` parameter on a [`Field`][pydantic.fields.Field] specifies whether the field should be validated in "strict mode".
In strict mode, Pydantic throws an error during validation instead of coercing data on the field where `strict=True`.

```py
Expand Down Expand Up @@ -761,62 +766,43 @@ See the [Serialization] section for more details.

## Customizing JSON Schema

There are fields that exclusively to customise the generated JSON Schema:
Some field parameters are used exclusively to customize the generated JSON schema. The parameters in question are:

* `title`
* `description`
* `examples`
* `json_schema_extra`

Read more about JSON schema customization / modification with fields in the [Customizing JSON Schema] section of the JSON schema docs.

* `title`: The title of the field.
* `description`: The description of the field.
* `examples`: The examples of the field.
* `json_schema_extra`: Extra JSON Schema properties to be added to the field.
## The `computed_field` decorator

??? api "API Documentation"
[`pydantic.fields.computed_field`][pydantic.fields.computed_field]<br>

The `computed_field` decorator can be used to include `property` or `cached_property` attributes when serializing a
model or dataclass. This can be useful for fields that are computed from other fields, or for fields that
are expensive to computed (and thus, are cached).

Here's an example:

```py
from pydantic import BaseModel, EmailStr, Field, SecretStr
from pydantic import BaseModel, computed_field


class User(BaseModel):
age: int = Field(description='Age of the user')
email: EmailStr = Field(examples=['marcelo@mail.com'])
name: str = Field(title='Username')
password: SecretStr = Field(
json_schema_extra={
'title': 'Password',
'description': 'Password of the user',
'examples': ['123456'],
}
)
class Box(BaseModel):
width: float
height: float
depth: float

@computed_field
def volume(self) -> float:
return self.width * self.height * self.depth

print(User.model_json_schema())
"""
{
'properties': {
'age': {
'description': 'Age of the user',
'title': 'Age',
'type': 'integer',
},
'email': {
'examples': ['marcelo@mail.com'],
'format': 'email',
'title': 'Email',
'type': 'string',
},
'name': {'title': 'Username', 'type': 'string'},
'password': {
'description': 'Password of the user',
'examples': ['123456'],
'format': 'password',
'title': 'Password',
'type': 'string',
'writeOnly': True,
},
},
'required': ['age', 'email', 'name', 'password'],
'title': 'User',
'type': 'object',
}
"""

b = Box(width=1, height=2, depth=3)
print(b.model_dump())
#> {'width': 1.0, 'height': 2.0, 'depth': 3.0, 'volume': 6.0}
```


Expand All @@ -828,3 +814,5 @@ print(User.model_json_schema())
[frozen dataclass documentation]: https://docs.python.org/3/library/dataclasses.html#frozen-instances
[Validate Assignment]: models.md#validate-assignment
[Serialization]: serialization.md#model-and-field-level-include-and-exclude
[Customizing JSON Schema]: json_schema.md#field-level-customization
[annotated]: https://docs.python.org/3/library/typing.html#typing.Annotated

0 comments on commit 22e6444

Please sign in to comment.