No, model_dump cannot return an exact type.

However, you don't have to use model_dump. Consider providing all the values explicitly instead. This way you won't be able to forget a required field.

Either you get an error that UserCreate has no attribute defined

user = UserCreate(name="John")

# error: "UserCreate" has no attribute "age" [attr-defined]
User(name=user.name, age=user.age)

or that you haven't provided a required attribute

user = UserCreate(name="John")

# error: Missing named argument "age" for "User"
User(name=user.name)
Answer from Paweł Rubin on Stack Overflow
🌐
Pydantic
docs.pydantic.dev › latest › concepts › serialization
Serialization - Pydantic Validation
When using the Python mode, Pydantic models (and model-like types such as dataclasses) (1) will be (recursively) converted to dictionaries. This is achievable by using the model_dump() method:
🌐
Pydantic
docs.pydantic.dev › latest › concepts › models
Models - Pydantic Validation
See Validating data. model_construct(): Creates models without running validation. See Creating models without validation. model_dump(): Returns a dictionary of the model's fields and values.
Discussions

`model_dump` doesn't work recursively with subclasses as expected
Initial Checks I confirm that I'm using Pydantic V2 Description When having a structure like this where an attribute type common: Common is the super type of the two possible options SubCommon1 | SubCommon2, a call to model_dump only yie... More on github.com
🌐 github.com
4
November 23, 2023
model_dump does not dump nested BaseModel
I am building a system within my microservices (with FastAPI) for handling more complex errors by giving context about a particular error. I noticed that my context BaseModel(s) don't get model_dump'd and simply appear as an empty dictionary, but when calling print(my_pydantic_model), I can ... More on github.com
🌐 github.com
3
August 11, 2023
model.model_dump() 'include' option should take precedence over 'exclude_defaults' option
Initial Checks I confirm that I'm using Pydantic V2 Description model_dump method should always include fields if they listed in 'include' option as it is more specific then exclude_def... More on github.com
🌐 github.com
3
March 7, 2024
How to dump a list of pydantic instances into a list of dicts?
That's strange, the list should be JSON serializable, but I'm inclined to think that it is due to pydantic_encoder misuse - it should be used only with json.dumps(..., default=pydantic_encoder). More on github.com
🌐 github.com
1
5
May 19, 2022
🌐
Pydantic
docs.pydantic.dev › 2.3 › usage › serialization
Serialization - Pydantic
The one exception to sub-models being converted to dictionaries is that RootModel and its subclasses will have the root field value dumped directly, without a wrapping dictionary. This is also done recursively. ... from typing import Any, List, Optional from pydantic import BaseModel, Field, Json class BarModel(BaseModel): whatever: int class FooBarModel(BaseModel): banana: Optional[float] = 1.1 foo: str = Field(serialization_alias='foo_alias') bar: BarModel m = FooBarModel(banana=3.14, foo='hello', bar={'whatever': 123}) # returns a dictionary: print(m.model_dump()) #> {'banana': 3.14, 'foo':
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › exporting_models
Exporting models - Pydantic
ujson generally cannot be used to dump JSON since it doesn't support encoding of objects like datetimes and does not accept a default fallback function argument. To do this, you may use another library like orjson. ... from datetime import datetime import orjson from pydantic import BaseModel def orjson_dumps(v, *, default): # orjson.dumps returns bytes, to match standard json.dumps we need to decode return orjson.dumps(v, default=default).decode() class User(BaseModel): id: int name = 'John Doe' signup_ts: datetime = None class Config: json_loads = orjson.loads json_dumps = orjson_dumps user = User.parse_raw('{"id":123,"signup_ts":1234567890,"name":"John Doe"}') print(user.json()) #> {"id":123,"signup_ts":"2009-02-13T23:31:30+00:00","name":"John Doe"}
🌐
GitHub
github.com › pydantic › pydantic › issues › 8213
`model_dump` doesn't work recursively with subclasses as expected · Issue #8213 · pydantic/pydantic
November 23, 2023 - class Holder(BaseModel): type: Literal["sub1", "sub2"] common: Common def model_dump(self): data = super().model_dump() data["common"] = self.common.model_dump() return data · from abc import ABC from typing import Literal from pydantic import BaseModel, model_validator class Common(BaseModel, ABC): shared_value: int class SubCommon1(Common): sub1_value: str class SubCommon2(Common): sub2_value: str class Holder(BaseModel): type: Literal["sub1", "sub2"] common: Common h = Holder.model_validate( { "common": SubCommon1.model_validate({"sub1_value": "A", "shared_value": 1}), "type": "sub1", } ) h.model_dump() # {'type': 'sub1', 'common': {'shared_value': 1}} h.common.model_dump() # {'shared_value': 1, 'sub1_value': 'A'}
Author   ThomasMarwitzQC
Find elsewhere
🌐
GitHub
github.com › pydantic › pydantic › issues › 7093
model_dump does not dump nested BaseModel · Issue #7093 · pydantic/pydantic
August 11, 2023 - """ self.service = service self.context = context self.error_code = f"{self.service}.{self.__class__.__name__}" def to_base_model(self, detail: str) -> VsBaseErrorSchema: """ Convert this exception to a Pydantic BaseModel :param detail: Human readable string describing the error message :return: """ return VsBaseErrorSchema(detail=detail, context=self.context, error_code=self.error_code) class ReconFieldMismatchError(VsBaseError): """Represents an error within the Amazon microservice when a Reconciliation field is mismatched with the Disbursement XML""" def __init__(self, field_name: str, user
Author   hlafaille
🌐
GitHub
github.com › pydantic › pydantic › issues › 8970
model.model_dump() 'include' option should take precedence over 'exclude_defaults' option · Issue #8970 · pydantic/pydantic
March 7, 2024 - from pydantic import BaseModel class Test(BaseModel): a: int = 0 b: str = "b" test = Test() print(test.model_dump(exclude_defaults=True, include={"a"})) # Output: {} # Expected: {'a': 0}
Author   tmax22
🌐
GitHub
github.com › pydantic › pydantic › discussions › 4456
Serialisation and Dumping · pydantic/pydantic · Discussion #4456
The precise semantics of when include trumps exclude is inherently complex, it would be good if we could remove include from Field and only allow it via model_dump. Similar to the blog post, we need the following output formats: Python objects - models are converted to dicts, nothing else is changed · JSON compatible python - objects are converted to dict, list, str, int, float, bool, None ... All these formats should be customisable via functions - obviously 2 and 3 should use the same customisation logic. The plan is to implement as much of this logic as possible in rust within pydantic-core.
Author   pydantic
🌐
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
🌐
Medium
medium.com › @kishanbabariya101 › episode-10-functional-serializers-in-pydantic-0175cdec2e69
Episode 10: Functional Serializers in Pydantic | by Kishan Babariya | Medium
December 18, 2024 - Serialization refers to converting an object into a format that can be easily stored or transferred. In Pydantic: Default Serialization: Models have a built-in .model_dump() method (formerly .dict()) to serialize data into Python dictionaries.
🌐
Pydantic
docs.pydantic.dev › latest › api › base_model
BaseModel - Pydantic Validation
Source code in pydantic/main.py · model_dump( *, mode: Literal["json", "python"] | str = "python", 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 ) -> dict[str, Any] Usage Documentation ·
🌐
Reddit
reddit.com › r/python › what problems does pydantic solves? and how should it be used
r/Python on Reddit: What problems does pydantic solves? and How should it be used
October 2, 2023 -

Hi Folks,I have been pondering on this question for sometime. But have not been able to get this. Searched internet but didn't find any article or video of help. Most of them talk about syntax and semantics of pydantic and none talked about what I wanted to know.

Asking this question, Because, in the first look pydantic looks helpful. as it helps us know what exact data is flowing through the application, helps us validate data. But it also takes the simplicity and flexibility that python provides us such as suppose, you may assign some intermediatry key in the dictionary pass that dictionary to some function pop that value out and use it.

using libraries like pydantic will make doing these things to put a little more effort and also the overhead of maintaining pydantic models comes. and in some scenario, some bug may be come up due to incorrect use of these kinds of libraries.

Well, the purpose of my question is not to question the usuability of pydantic. I know it is definitely useful as it is being used widely. but to understand how to use it perfectly and to understand where not to use it.

🌐
FastAPI
fastapi.tiangolo.com › tutorial › extra-models
Extra Models - FastAPI
That way, we can declare just the differences between the models (with plaintext password, with hashed_password and without password): ... from fastapi import FastAPI from pydantic import BaseModel, EmailStr app = FastAPI() class UserBase(BaseModel): username: str email: EmailStr full_name: str | None = None class UserIn(UserBase): password: str class UserOut(UserBase): pass class UserInDB(UserBase): hashed_password: str def fake_password_hasher(raw_password: str): return "supersecret" + raw_password def fake_save_user(user_in: UserIn): hashed_password = fake_password_hasher(user_in.password) user_in_db = UserInDB(**user_in.model_dump(), hashed_password=hashed_password) print("User saved!
🌐
GitHub
github.com › pydantic › pydantic › issues › 8907
model_dump converts file objects / streams to `SerializationIterator` · Issue #8907 · pydantic/pydantic
February 27, 2024 - class DocumentUpload(BaseModel): file: Any = None myUpload = DocumentUpload( file = open("some_file.png", "rb") ) dump = myUpload.model_dump() dump will have the file buried within a SerializationIterator · When printed, it outputs: ...
Author   benogle
🌐
Pydantic
docs.pydantic.dev › 2.4 › concepts › models
Models - Pydantic
More details on pydantic's coercion logic can be found in Data Conversion. Fields of a model can be accessed as normal attributes of the user object. The string '123' has been converted into an int as per the field type. ... The fields which were supplied when user was initialized. assert user.model_dump() == {'id': 123, 'name': 'Jane Doe'}
🌐
YouTube
youtube.com › watch
How to Cleanly Initialize a Pydantic Model from Another ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Reddit
reddit.com › r/python › dynapydantic: dynamic tracking of pydantic models and polymorphic validation
r/Python on Reddit: dynapydantic: Dynamic tracking of pydantic models and polymorphic validation
February 6, 2026 -

Repo Link: https://github.com/psalvaggio/dynapydantic

What My Project Does

TLDR: It's like `SerializeAsAny`, but for both serialization and validation.

Target Audience

Pydantic users. It is most useful for models that include inheritance trees.

Comparison

I have not see anything else, the project was motivated by this GitHub issue: https://github.com/pydantic/pydantic/issues/11595

I've been working on an extension module for `pydantic` that I think people might find useful. I'll copy/paste my "Motivation" section here:

Consider the following simple class setup:

import pydantic

class Base(pydantic.BaseModel):
    pass

class A(Base):
    field: int

class B(Base):
    field: str

class Model(pydantic.BaseModel):
    val: Base

As expected, we can use A's and B's for Model.val:

>>> m = Model(val=A(field=1))
>>> m
Model(val=A(field=1))

However, we quickly run into trouble when serializing and validating:

>>> m.model_dump()
{'base': {}}
>>> m.model_dump(serialize_as_any=True)
{'val': {'field': 1}}
>>> Model.model_validate(m.model_dump(serialize_as_any=True))
Model(val=Base())

Pydantic provides a solution for serialization via serialize_as_any (and its corresponding field annotation SerializeAsAny), but offers no native solution for the validation half. Currently, the canonical way of doing this is to annotate the field as a discriminated union of all subclasses. Often, a single field in the model is chosen as the "discriminator". This library, dynapydantic, automates this process.

Let's reframe the above problem with dynapydantic:

import dynapydantic
import pydantic

class Base(
    dynapydantic.SubclassTrackingModel,
    discriminator_field="name",
    discriminator_value_generator=lambda t: t.__name__,
):
    pass

class A(Base):
    field: int

class B(Base):
    field: str

class Model(pydantic.BaseModel):
    val: dynapydantic.Polymorphic[Base]

Now, the same set of operations works as intended:

>>> m = Model(val=A(field=1))
>>> m
Model(val=A(field=1, name='A'))
>>> m.model_dump()
{'val': {'field': 1, 'name': 'A'}}
>>> Model.model_validate(m.model_dump())
Model(val=A(field=1, name='A')