Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add replacement for 'ENCODER_BY_TYPE' to migration guide #8501

Merged
merged 4 commits into from Jan 12, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/migration.md
Expand Up @@ -997,3 +997,31 @@ For `ConstrainedStr` you can use [`StringConstraints`][pydantic.types.StringCons
- `pydantic.utils.path_type`
- `pydantic.utils.validate_field_name`
- `pydantic.validate_model`

## Customizing JSON Encoding for Pydantic Model with `ObjectId` Field in V2

To ensure that instances of the model are serialized to JSON with the `ObjectId` field represented as a string, use a custom JSON encoder for instances of `ObjectId` since `ENCODERS_BY_TYPE` class is removed. For example:

```
from pydantic.json import ENCODERS_BY_TYPE
from bson import ObjectId
ENCODERS_BY_TYPE[ObjectId] = lambda v: str(v)
```

becomes:
```
from bson import ObjectId
from pydantic import BaseModel, ConfigDict

BaseModel.model_config["json_encoders"] = {ObjectId: lambda v: str(v)}


class Item(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)

id: ObjectId


item = Item(id=ObjectId("5ff1e194b6a9d7a5f9a2741c"))
print(item.model_dump_json())
```