pydantic / pydantic-core

Core validation logic for pydantic written in rust
MIT License
1.34k stars 207 forks source link

Fix model field serializer with computed field #1349

Open nix010 opened 1 week ago

nix010 commented 1 week ago

Change Summary

Related issue number

fix #1348

Checklist

Selected Reviewer: @samuelcolvin

nix010 commented 1 week ago

Updated: Figured it out ! tests added

I know the commit didn't come with the test but how do I do


import pydantic
from typing import Any

class MyModel(pydantic.BaseModel):

    other_field: int = 42

    @pydantic.computed_field
    @property
    def my_field(self) -> str:
        return "foo1"

    @pydantic.field_serializer("*")
    def my_field_serializer(self, value: Any, info: pydantic.FieldSerializationInfo) -> Any:
        print(f"{info.field_name} = {value}")
        return value

but MyModel with the SchemaSerializer and model_fields_schema like other tests in tests/serializers/test_model.py

codecov[bot] commented 1 week ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

:loudspeaker: Thoughts on this report? Let us know!

codspeed-hq[bot] commented 1 week ago

CodSpeed Performance Report

Merging #1349 will not alter performance

Comparing nix010:fix-field-serializer-with-computed-field (cc80ddf) with main (0e6b377)

Summary

✅ 155 untouched benchmarks

nix010 commented 1 week ago

please review

nix010 commented 1 week ago

The failed CI I think origin from the ruff version ! open to suggestions on fixing those

nix010 commented 1 week ago

Looking good so far - I've added a few change requests.

Have you used this version of pydantic-core locally to make sure that all pydantic tests pass, specifically the one included in the OP's issue?

yep.

import pydantic
from typing import Any

class MyModel(pydantic.BaseModel):

    other_field: int = 42

    @pydantic.computed_field
    @property
    def my_field(self) -> str:
        return "foo1"

    @pydantic.field_serializer("*")
    def my_field_serializer(self, value: Any, info: pydantic.FieldSerializationInfo) -> Any:
        print(f"{info.field_name} = {value}")
        return value

print(MyModel().model_dump())
print(MyModel().model_dump_json())

"""
other_field = 42
my_field = foo1
{'other_field': 42, 'my_field': 'foo1'}
other_field = 42
my_field = foo1
{"other_field":42,"my_field":"foo1"}
"""