Skip to content

Commit

Permalink
Fix PydanticObjectId types being parsed as strings when using Pydan…
Browse files Browse the repository at this point in the history
…tic's `model_validate_json`

Unsure if this could be fixed in a more stylish fashion, but it was simply incorrectly setup before, at least now it works. 

**Please make as many changes as needed if this solution could be improved.**

I believe this bugfix is quite important. If you parse an ID (let's call the variable `identifier`) from a JSON file in order to look it up on your Mongo database... you won't find it.

```python
 await cls.find_one(cls.id == identifier)
```
will return `None` even if the object exists, because `identifier` will be of type `str` instead of `ObjectId` when parsing from a JSON file with Pydantic's `model_validate_json`. 

Fixes BeanieODM#940.
  • Loading branch information
ivan-gj authored Oct 14, 2024
1 parent 3421d55 commit 1d66d97
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion beanie/odm/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def __get_pydantic_core_schema__(
) -> CoreSchema: # type: ignore
return core_schema.json_or_python_schema(
python_schema=plain_validator(cls.validate),
json_schema=str_schema(),
json_schema=plain_validator(cls.validate),
serialization=core_schema.plain_serializer_function_ser_schema(
lambda instance: str(instance), when_used="json"
),
Expand Down

0 comments on commit 1d66d97

Please sign in to comment.