Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings
Discussion options

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:

class Model(BaseModel):
    foo: str | None = None

    @field_serializer('foo')
    def _serialize_foo(cls, v):
        if v == 'spam':
            return NotSerialized  # a special unique constant to mark the field as excluded
        return v

Also when using the serialization context:

class Model(BaseModel):
    foo: int | None = None

    @field_serializer('foo')
    def _serialize_foo(cls, v, info):
        if info.context and info.context.get('foo_rule') == 'spam':
            return NotSerialized  # a special unique constant to mark the field as excluded
        return v

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.

You must be logged in to vote

Replies: 1 comment · 1 reply

Comment options

pydantic_core.PydanticOmit would be the way to do so but iirc it isn't usable yet for serialization. Alternatively, you can define a model serializer:

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 v

pydantic/pydantic-core#1535 should also cover the use case.

You must be logged in to vote
1 reply
@espdev
Comment options

Yes, I have already used model_serializer in some cases.
exclude_if looks very reasonable. Thank you for the info about it! Hopefully this will be accepted and added to Pydantic in some form.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.