Skip to content

Post-parsing middleware / coercing explicit nulls in requests to default values #11457

Answered by YuriiMotov
acdha asked this question in Questions
Discussion options

You must be logged in to vote

IMO, the easiest way to remove nulls in input data is to implement model_validator for base model and use this base model for all your models:


from typing import Any

from pydantic import BaseModel, Field, model_validator


class MyBaseModel(BaseModel):

    @model_validator(mode="before")
    @classmethod
    def remove_nulls(cls, data: dict[str, Any] | Any) -> dict[str, Any] | Any:
        if not isinstance(data, dict):
            return data
        for key in list(data.keys()):
            if data[key] is None:
                data.pop(key)
        return data


class Item(MyBaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = Field(d…

Replies: 1 comment 1 reply

Comment options

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

Answer selected by acdha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
2 participants