Anton Ovsyannikov
Anton Ovsyannikov

Reputation: 1190

Pydantic: how to make model with some mandatory and arbitrary number of other optional fields, which names are unknown and can be any?

I'd like to represent the following json by Pydantic model:

{
   "sip" {
     "param1": 1
   }
   "param2": 2
   ...
}

Means json may contain sip field and some other field, any number any names, so I'd like to have model which have sip:Optional[dict] field and some kind of "rest", which will be correctly parsed from/serialized to json. Is it possible?

Upvotes: 1

Views: 1585

Answers (1)

Hernán Alarcón
Hernán Alarcón

Reputation: 4089

Maybe you are looking for the extra model config:

extra

whether to ignore, allow, or forbid extra attributes during model initialization. Accepts the string values of 'ignore', 'allow', or 'forbid', or values of the Extra enum (default: Extra.ignore). 'forbid' will cause validation to fail if extra attributes are included, 'ignore' will silently ignore any extra attributes, and 'allow' will assign the attributes to the model.

Example:

from typing import Any, Dict, Optional

import pydantic


class Foo(pydantic.BaseModel):
    sip: Optional[Dict[Any, Any]]

    class Config:
        extra = pydantic.Extra.allow


foo = Foo.parse_raw(
    """
{
   "sip": {
     "param1": 1
   },
   "param2": 2
}
"""
)

print(repr(foo))
print(foo.json())

Output:

Foo(sip={'param1': 1}, param2=2)
{"sip": {"param1": 1}, "param2": 2}

Upvotes: 1

Related Questions