Pydantic will exclude the class variables which begin with an underscore. so if it fits your use case, you can rename your attribues.

class User(UserBase):
    _user_id=str
    some_other_field=str
    ....
Answer from N.Moudgil on Stack Overflow
🌐
Pydantic
docs.pydantic.dev › latest › concepts › serialization
Serialization - Pydantic Validation
The exclude parameter can be used to specify which fields should be excluded (including the others), and vice-versa using the include parameter. # using a set: print(t.model_dump(exclude={'user', 'value'})) #> {'id': '1234567890'} # using a ...
Discussions

Is there a way to have extra fields excluded during model_dump?
I have a complex model which needs to accept extra fields, but I want to be able to save a version without the extras using model_dump. ... Beta Was this translation helpful? Give feedback. ... Here's the workaround I'm using now. Would be nice to just call .model_dump(ignore_extras) though :) from pydantic ... More on github.com
🌐 github.com
2
1
December 1, 2023
Allow field exclusion for nested models AND/OR allow field additions for `model_dump`
I would like to be able to define ... occurrences when calling model_dump at runtime (ie not using exclude on the Field definition) . See below example for an attempt that does NOT work: # Trying nested properties from typing import Optional from pydantic import BaseModel, Field, ... More on github.com
🌐 github.com
4
December 12, 2024
Dynamically include/exclude fields from dumps
Initial Checks I have searched Google & GitHub for similar requests and couldn't find anything I have read and followed the docs and still think this feature is missing Description I am wri... More on github.com
🌐 github.com
1
May 30, 2024
model_dump include/exclude attributes by alias
I need to extract info from a pydantic model using model_dump. Is there any way to find the attributes to include/exclude by aliases? More on github.com
🌐 github.com
3
May 13, 2024
🌐
GitHub
github.com › pydantic › pydantic › discussions › 7114
Exclude a computed field · pydantic/pydantic · Discussion #7114
August 14, 2023 - I have a pydantic model and I want to have some properties I can cache, but have nothing to do with dumping the model. Just a function that caches itself and I can call it without parenthesis for backwards compatibility. ... from __future__ import annotations import json from typing import Any, Literal from pydantic import computed_field from pydantic.dataclasses import dataclass @dataclass(slots=True, frozen=True) class Response: request: Request url: str status_code: int body: list[int] | None = None # bytes headers: dict[str, str] | None = None @computed_field # type: ignore[misc] @property def content(self) -> str | None: if self.body is None: msg = 'Response body is not available.
Author   pydantic
🌐
GitHub
github.com › pydantic › pydantic › discussions › 8251
Is there a way to have extra fields excluded during model_dump? · pydantic/pydantic · Discussion #8251
December 1, 2023 - from pydantic import BaseModel, ConfigDict class Nested(BaseModel): model_config = ConfigDict(extra="allow") baz: str class Root(BaseModel): foo: int = 10 bar: int nested: Nested def remove_extras(model: BaseModel, data: dict) -> dict: """Recursively removes extra keys from the dumped version of a Model""" if model.model_extra: for key in model.model_extra.keys(): data.pop(key, None) for fieldname, field_info in model.model_fields.items(): value = getattr(model, fieldname) if hasattr(value, "model_extra"): data[fieldname] = remove_extras(value, data[fieldname]) return data if __name__ == "__main__": model = Root( foo=10, bar=20, nested={"baz": "boing", "extra": "so special"}, ) dumped_data = model.model_dump() dumped_data = remove_extras(model, dumped_data) assert "extra" not in dumped_data["nested"]
Author   pydantic
🌐
GitHub
github.com › pydantic › pydantic › issues › 11099
Allow field exclusion for nested models AND/OR allow field additions for `model_dump` · Issue #11099 · pydantic/pydantic
December 12, 2024 - I would like to be able to define a field on a model that can be removed in all nested occurrences when calling model_dump at runtime (ie not using exclude on the Field definition) . See below example for an attempt that does NOT work: # Trying nested properties from typing import Optional from pydantic import BaseModel, Field, field_validator class BaseModel2(BaseModel): class_name: Optional[str] = Field(None, validate_default=True) @field_validator("class_name") @classmethod def set_class_name(cls, v): if v is None: return cls.__name__ else: raise ValueError("class_name must not be set") cla
Author   maxschulz-COL
🌐
Pydantic
docs.pydantic.dev › latest › concepts › fields
Fields - Pydantic Validation
The exclude and exclude_if parameters can be used to control which fields should be excluded from the model when exporting the model.
🌐
GitHub
github.com › pydantic › pydantic › issues › 9528
Dynamically include/exclude fields from dumps · Issue #9528 · pydantic/pydantic
May 30, 2024 - I use a wildcard field_serializer ... (Mutability.readWrite, Mutability.writeOnly)}) However, the field_serializer does not allow to exclude the field from serialization....
Published   May 30, 2024
Author   azmeuk
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › exporting_models
Exporting models - Pydantic
This is the primary way of converting a model to a dictionary. Sub-models will be recursively converted to dictionaries. ... exclude_unset: whether fields which were not explicitly set when creating the model should be excluded from the returned dictionary; default False.
Find elsewhere
🌐
GitHub
github.com › pydantic › pydantic › issues › 9428
model_dump include/exclude attributes by alias · Issue #9428 · pydantic/pydantic
May 13, 2024 - I need to extract info from a pydantic model using model_dump. Is there any way to find the attributes to include/exclude by aliases?
Published   May 13, 2024
Author   pablofueros
🌐
Sentry
sentry.io › sentry answers › fastapi › exclude one or more fields in pydantic model from appearing in fastapi responses
Exclude one or more fields in Pydantic model from appearing in FastAPI responses | Sentry
In this case, we’ll use it to exclude the address and created_at fields from our API’s responses: from pydantic import BaseModel, Field # also import Field from datetime import datetime from typing import Annotated # import Annotated class User(BaseModel): username: str email: str address: Annotated[str, Field(exclude=True)] created_at: Annotated[datetime, Field(exclude=True)]
🌐
Pydantic
docs.pydantic.dev › 2.3 › usage › serialization
Serialization - Pydantic
In this scenario, model_dump and related methods expect integer keys for element-wise inclusion or exclusion. To exclude a field from every member of a list or tuple, the dictionary key '__all__' can be used, as shown here:
🌐
Pydantic
docs.pydantic.dev › latest › api › base_model
BaseModel - Pydantic Validation
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. ... model_dump_json( *, indent: int | None = None, ensure_ascii: bool = False, include: IncEx | None = None, exclude: IncEx | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: ( bool | Literal["none", "warn", "error"] ) = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False ) -> str
🌐
Reddit
reddit.com › r/learnpython › pydantic v2 exclude parameter in field and annotated
r/learnpython on Reddit: Pydantic v2 exclude parameter in Field and Annotated
January 1, 2024 -

I am playing around with Pydantic v2.5 and trying to see how the exclude works when set as a Field option. Let's imagine that I have a User BaseModel class and a Permissions BaseModel class. Both are used in the Config class.

We do not want to print the all User info, hence why I added the exclude in the Permissions class when the user is defined.

from typing import Annotated, Optional
from pydantic import BaseModel, Field


class User(BaseModel):
    name: str
    surname: str
    card_id: str


class Permissions(BaseModel):
    user: Annotated[User, Field(exclude=True)]
    config_rule: str


class Config:
    def __init__(self):
        self.user = User(**dict(name="Name", surname="Surname", card_id="12343545"))
        self.config_data = Permissions(user=self.user, config_rule="admin")

c = Config()
print(c.config_data.model_dump_json(indent=2))

In this case, the exclude set in the Permissions class seems to be working fine, in fact the print output is:

{
  "config_rule": "admin"
}

However, if I change the Permissions class with:

class Permissions(BaseModel):
    user: Optional[Annotated[User, Field(exclude=True)]]
    config_rule: str

The output is:

{
  "user": {
    "name": "Name",
    "surname": "Surname",
    "card_id": "12343545"
  },
  "config_rule": "admin"
}

And I am not sure I understand why. Any thoughts? Thanks.

Top answer
1 of 2
4

According to the documentation on computed_field:

computed_field

Decorator to include property and cached_property when serializing models or dataclasses.

This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached.

In other words, if don't want to include (= exclude) a field we shouldn't use computed_field decorator:

from __future__ import annotations
import pydantic
from pprint import pprint

class System(pydantic.BaseModel):
    id: int
    name: str
    subsystems: list[System] | None = None

    # comment or remove it
    # @pydantic.computed_field()
    @property
    def computed(self) -> str:
        return self.name.upper()


systems = System(
    id=1,
    name="Main system",
    subsystems=[
        System(id=2, name="Subsystem A"),
        System(id=3, name="Subsystem B"),
    ],
)
pprint(systems.model_dump(), indent=2)
print(systems.computed)  # but it is still there

Output is:

{ 'id': 1,
  'name': 'Main system',
  'subsystems': [ {'id': 2, 'name': 'Subsystem A', 'subsystems': None},
                  {'id': 3, 'name': 'Subsystem B', 'subsystems': None}]}
MAIN SYSTEM
2 of 2
-1

You can create a function to serialize what you want. Here, I use a function to return dict and exclude computed

from __future__ import annotations
import pydantic
from pprint import pprint


class System(pydantic.BaseModel):
    id: int
    name: str
    subsystems: list[System] | None = None

    @pydantic.computed_field()
    @property
    def computed(self) -> str:
        return self.name.upper()

    def as_dict(self):
        return {
            "id": self.id,
            "name": self.name,
            "subsystems": [i.model_dump(exclude={'computed'}) for i in self.subsystems]
        }


systems = System(
    id=1,
    name="Main system",
    subsystems=[
        System(id=2, name="Subsystem A"),
        System(id=3, name="Subsystem B"),
    ],
)
pprint(systems.as_dict(), indent=2)
Top answer
1 of 2
2

You can create your MyBaseModel class from BaseModel, where you can add model serializer (with mode="wrap").

In this model serializer just exclude from result dict all fields which are not present in the self.model_fields.

Now inherit all your models from MyBaseModel and enjoy!

from typing import Any
from pydantic import BaseModel, ConfigDict, model_serializer, SerializerFunctionWrapHandler, FieldSerializationInfo


class MyBaseModel(BaseModel):
    @model_serializer(mode="wrap")
    def _serialize(self, handler):
        d = handler(self)
        d = {k:v for k, v in d.items() if k in self.model_fields}
        return d


class Nested(MyBaseModel):

    model_config = ConfigDict(extra="allow")

    baz: str


class Root(MyBaseModel):

    foo: int = 10
    bar: int
    nested: Nested


if __name__ == "__main__":

    model = Root(foo=10, bar=20, nested={"baz": "boing", "extra": "so special"})

    dumped_data = model.model_dump()

    assert "extra" not in dumped_data["nested"]
2 of 2
-1

Update: For Pydantic 2.x and if you are looking to exclude a nested key for all occurances, you can use the key __all__ like so:

dumped_data = model.model_dump(exclude={'__all__': {'extra'}})

Example from Documentation (https://docs.pydantic.dev/latest/concepts/serialization/#advanced-include-and-exclude):

class User(BaseModel):
    first_name: str
    second_name: str
    address: Address
    card_details: CardDetails
    hobbies: List[Hobby]
user = User(
    first_name='John',
    second_name='Doe',
    address=Address(
        post_code=123456, country=Country(name='USA', phone_code=1)
    ),
    card_details=CardDetails(
        number='4212934504460000', expires=datetime.date(2020, 5, 1)
    ),
    hobbies=[
        Hobby(name='Programming', info='Writing code and stuff'),
        Hobby(name='Gaming', info='Hell Yeah!!!'),
    ],
)
(...)
print(user.model_dump(exclude={'hobbies': {'__all__': {'info'}}}))

🌐
Netlify
field-idempotency--pydantic-docs.netlify.app › usage › exporting_models
Exporting models - pydantic
exclude_unset: whether fields which were not explicitly set when creating the model should be excluded from the returned dictionary; default False. Prior to v1.0, exclude_unset was known as skip_defaults; use of skip_defaults is now deprecated · exclude_defaults: whether fields which are equal ...
🌐
Pydantic
docs.pydantic.dev › latest › api › config
Configuration - Pydantic Validation
The = Field(init=False) does not have any effect at runtime, but prevents the __pydantic_extra__ field from being included as a parameter to the model's __init__ method by type checkers. As well as specifying an extra configuration value on the model, you can also provide it as an argument to the validation methods. This will override any extra configuration value set on the model: from pydantic import BaseModel, ConfigDict, ValidationError class Model(BaseModel): x: int model_config = ConfigDict(extra="allow") try: # Override model config and forbid extra fields just this time Model.model_validate({"x": 1, "y": 2}, extra="forbid") except ValidationError as exc: print(exc) """ 1 validation error for Model y Extra inputs are not permitted [type=extra_forbidden, input_value=2, input_type=int] """
🌐
GitHub
github.com › pydantic › pydantic › discussions › 9393
`model_dump()`'s `exclude` keyword argument doesn't exclude keys named the same thing in nested models · pydantic/pydantic · Discussion #9393
Subclasses pydantic.BaseModel · class AuroraBaseModel(BaseModel): """Base class for all models in Aurora.""" model_config = ConfigDict(ignored_types=(Red,), arbitrary_types_allowed=True) bot: Red def to_json(self, indent: int = None, file: Any = None, **kwargs): from aurora.utilities.json import dump, dumps return dump(self.model_dump(exclude={"bot"}), file, indent=indent, **kwargs) if file else dumps(self.model_dump(exclude={"bot"}), indent=indent, **kwargs) Subclasses AuroraBaseModel ·
Author   pydantic