Virgil Raitz
Virgil Raitz

Reputation: 51

Printing Pydantic objects with Schema definitions included?

I have a Pydantic model like

from datetime import datetime
from pydantic import BaseModel, Field


class MainModel(BaseModel):
    name: str = Field(
        "example",
        title='The name',
        description='The name assigned',
    )
    date: datetime = Field(
        datetime.now(),
        title='Date',
        description='The date of creation...',
    )

Pydantic makes it easy to print out the model schema with MainModel.schema_json(). Once I have initialized an object of MainModel, such as

example = MainModel(
    name="test",
    date=datetime.now()
)

I can print json/dict of example by example.dict(), however, additional markup information like title and description aren't included. Is it possible to print these together, or will I need to do some sort of dict join between MainModel.schema_json() and example.dict()?

Upvotes: 5

Views: 8003

Answers (1)

MangoNrFive
MangoNrFive

Reputation: 1599

I don't know of any functionality like that in pydantic. But the dict join you have mentioned isn't too bad, e.g. like this:

def get_schema_and_data(instance):
    schema = instance.schema()
    for key, value in instance.dict().items():
        schema["properties"][key].update({"value": value})
    return schema


from pprint import pprint
pprint(get_schema_and_data(example))

Which results in:

{'properties': {'date': {'default': '2022-08-05T15:39:26.183702',
                         'description': 'The date of creation...',
                         'format': 'date-time',
                         'title': 'Date',
                         'type': 'string',
                         'value': datetime.datetime(2022, 8, 5, 15, 39, 26, 185091)},
                'name': {'default': 'example',
                         'description': 'The name assigned',
                         'title': 'The name',
                         'type': 'string',
                         'value': 'test'}},
 'title': 'MainModel',
 'type': 'object'}

If you have a nested pydantic-object it gets more complicated, but at that point you could write a function that recursively traverses the schema-dict by stripping apart the layers in the example.dict()-dict and inserting the values.

Upvotes: 5

Related Questions