Skip to content

Commit da8facb

Browse files
committed
feat: provide a field serializer in DandiBaseModel to handle types in anys
This serializer allows serialization of model instances containing field values that are of types from the anys pacakge, https://pypi.org/project/anys/. This is needed for tests that uses the anys types, such as the ones in dandi-cli. This solution was initially proposed at dandi/dandi-cli#1716 (comment)
1 parent fa9b7f6 commit da8facb

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

dandischema/models.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,11 @@
2626
EmailStr,
2727
Field,
2828
GetJsonSchemaHandler,
29+
SerializerFunctionWrapHandler,
2930
StringConstraints,
3031
TypeAdapter,
3132
ValidationInfo,
33+
field_serializer,
3234
field_validator,
3335
model_validator,
3436
)
@@ -508,6 +510,19 @@ def json_dict(self) -> dict:
508510
)
509511
return self.model_dump(mode="json", exclude_none=True)
510512

513+
@field_serializer("*", mode="wrap")
514+
def ignore_any_types(
515+
self, value: Any, handler: SerializerFunctionWrapHandler
516+
) -> Any:
517+
try:
518+
from anys import AnyBase
519+
except ImportError:
520+
pass
521+
else:
522+
if isinstance(value, AnyBase):
523+
return value
524+
return handler(value)
525+
511526
@field_validator("schemaKey")
512527
@classmethod
513528
def ensure_schemakey(cls, val: str) -> str:

0 commit comments

Comments
 (0)