You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If I understand the round_trip=True option correctly, I think it should ignore @computed_field ? With the example bellow, using extra='forbid' makes the round trip fails.
Example Code
fromtypingimportListfrompydanticimportBaseModel, Json, computed_field, ConfigDictclassModel(BaseModel):
json_obj: Json[List[int]]
model_config=ConfigDict(extra='forbid')
@computed_field@propertydeffirst(self) ->int:
returnself.json_obj[0]
dumped=Model(json_obj="[1, 2]").model_dump_json(round_trip=True)
print(dumped)
# > {"json_obj":"[1,2]","first":1}print(Model.model_validate_json(dumped))
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Model# first# Extra inputs are not permitted [type=extra_forbidden, input_value=1, input_type=int]
Apologies pretty low value contribution but a quick easy temporary "fix" for those affected is:
frompydanticimportBaseModel, model_serializer, SerializationInfoclassRoundTripModel(BaseModel):
@model_serializer(mode="wrap")def_pop_extra_fields_round_trip(self, handler, info: SerializationInfo):
""" Removes all computed fields to support serialize/deserialize when `round_trip=True`: https://github.com/pydantic/pydantic/issues/7158 Warning: A side effect of defining a `@model_serializer` is that any raised exceptions will be translated to `PydanticSerializationError` by `pydantic_core`. """result=handler(self)
ifinfo.round_trip:
ifinfo.by_alias:
excl= (f.aliasorkfork, finself.model_computed_fields.items())
else:
excl=self.model_computed_fieldsforkeyinexcl:
delresult[key]
returnresult
Edit 1: Fix excl behavior when alias is not defined.
Uh oh!
There was an error while loading. Please reload this page.
Initial Checks
Description
If I understand the
round_trip=True
option correctly, I think it should ignore@computed_field
? With the example bellow, usingextra='forbid'
makes the round trip fails.Example Code
Python, Pydantic & OS Version
Selected Assignee: @dmontagu
The text was updated successfully, but these errors were encountered: