[Python] In Pydantic 2, how do allow missing fields during deserialisation/validation, but...

Discussão em 'Python' iniciado por Stack, Agosto 10, 2025.

  1. Stack

    Stack Membro Participativo

    I use pydantic to be able to serialise and deserialise json data stored in a large database. Each of these json strings represent a pydantic model MyModel.

    class MyModel(BaseModel):
    attr1: int


    I am making changes to MyModel, so that it now has another attribute attr2. To preserve backwards compatibility with existing data, I want it so that when validating strings, a missing attr2 is given a default value. I can achieve that using this:

    class MyModel(BaseModel):
    attr1: int
    attr2: int = 5


    This allows me to call model_validate_json on strings like "'{"attr1": 1}'".

    I also need to manually create instances of MyModel. I want it so that when creating an instance, attr2 is required. This is to prevent myself from accidentally forgetting to set attr2 in the future.

    However I find that this doesn't work as I expect.

    my_model_instance_1 = MyModel(attr1=1, attr2=2)

    my_model_instance_2 = MyModel(attr1=1) # pydantic allows this, but I want this to be forbidden.



    How do I allow missing fields during validation, but forbid it in manual instantiation?

    Continue reading...

Compartilhe esta Página