How about using a special value in the field serializer to exclude a field? #11724
espdev
started this conversation in
Feature Request
Replies: 1 comment · 1 reply
-
|
from pydantic import BaseModel, SerializerFunctionWrapHandler, model_serializer
class Model(BaseModel):
foo: str = 'spam'
@model_serializer(mode='wrap')
def wrap_foo(self, handler: SerializerFunctionWrapHandler):
v = handler(self)
if v['foo'] == 'spam':
del v['foo']
return vpydantic/pydantic-core#1535 should also cover the use case. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello everyone!
Working a lot with Pydantic models I got the idea that it would be nice to be able to conditionally exclude fields during serialization.
The need to exclude a field may depend on the value of the field or, for example, on the serialization context. In this case, the exclusion rules could be controlled from within the serializer handler.
Here's a simple toy example of what I mean:
Also when using the serialization context:
This ability to control field exclusion rules directly from the serializer would be a useful more flexible addition to the existing exclusion mechanisms in Pydantic: Field(exclude=True), model_dump(exclude={}).
Perhaps it violates the architectural principles of the project or it already exists in some form and I just don't know about it.
What do you thing?
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions