Skip to content

Commit

Permalink
kernelci.api.model_base: update model_serializer
Browse files Browse the repository at this point in the history
Add a hack to handle `exclude` fields while dumping
model fields to dictionary.
The hack should be removed after a pydantic bug is
fixed: pydantic/pydantic#6575
Also, use `SerializationInfo` to get mode of serialization
and convert `ObjectId` fields to string only if `json`
response is required with `mode=json` in `model_dump`
function. That is due to other operations such as
inserting or updating objects in DB doesn't need the
conversion as data types should be `ObjectId` in the DB.

Signed-off-by: Jeny Sadadia <[email protected]>
  • Loading branch information
Jeny Sadadia committed Nov 8, 2024
1 parent 8549d0e commit 953ebc7
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions kernelci/api/models_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
BaseModel,
Field,
model_serializer,
SerializationInfo,
)
from pydantic.dataclasses import dataclass
from pydantic_core import core_schema
Expand Down Expand Up @@ -84,11 +85,26 @@ def update(self):
def get_indexes(cls):
"""Method to get indexes"""

@model_serializer(when_used='json')
def serialize_model(self) -> Dict[str, Any]:
"""Serializer for converting ObjectId to string"""
@model_serializer
def serialize_model(self, info: SerializationInfo) -> Dict[str, Any]:
"""Model serializer for the below custom handling:
- convert ObjectId fields to string
- handle `exclude` fields in serialized response
"""
values = self.__dict__.copy()

# TODO:

Check warning on line 96 in kernelci/api/models_base.py

View workflow job for this annotation

GitHub Actions / Lint

TODO:
# Remove manual handling of `exclude` fields below once
# the pydantic issue is fixed:
# https://github.com/pydantic/pydantic/issues/6575
if info.exclude:
for field in info.exclude:
values.pop(field, None)

Check failure on line 102 in kernelci/api/models_base.py

View workflow job for this annotation

GitHub Actions / Lint

Argument 1 to "pop" of "dict" has incompatible type "Union[int, str]"; expected "str" [arg-type]

for field_name, value in values.items():
if isinstance(value, ObjectId):
values[field_name] = str(value)
if info.mode == 'json':
values[field_name] = str(value)
else:
values[field_name] = value
return values

0 comments on commit 953ebc7

Please sign in to comment.