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

kernelci.api.model_base: update model_serializer #2738

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 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: # pylint: disable=fixme
# 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
Loading