Pydantic: Create a model from dict, excluding unknown fields

Created on 8 Jan 2021  路  2Comments  路  Source: samuelcolvin/pydantic

Question

Can we create a Pydantic model out of a dictionary that has extra fields?
For example, let's say I had a pydantic model User with the fields(first_name).

How can I do something like: User({"first_name": "test", "university": "test"}, exclude_unknown=True)?

I basically need to use Pydantic but partially disable validation. I'd still like to validate first_name, but just ignore last_name when constructing from an object.

The use case is that I have an API that returns too much information, and I'd like to ignore most of it when constructing my Pydantic model.

question

Most helpful comment

Hi @RamiAwar and happy new year!

By default a BaseModel will ignore extra fields. You can have a look at the config doc with the extra parameter.
So you can directly do

from pydantic import BaseModel


class User(BaseModel):
    first_name: str

user = User(**{"first_name": "test", "university": "test"})  # or User.parse_obj({...})

print(repr(User(first_name='test')))
# User(first_name='test')

All 2 comments

Hi @RamiAwar and happy new year!

By default a BaseModel will ignore extra fields. You can have a look at the config doc with the extra parameter.
So you can directly do

from pydantic import BaseModel


class User(BaseModel):
    first_name: str

user = User(**{"first_name": "test", "university": "test"})  # or User.parse_obj({...})

print(repr(User(first_name='test')))
# User(first_name='test')

Thanks! I didn't know that :D Happy new year @PrettyWood!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

engstrom picture engstrom  路  3Comments

dconathan picture dconathan  路  3Comments

drpoggi picture drpoggi  路  3Comments

iwoloschin picture iwoloschin  路  3Comments

ashpreetbedi picture ashpreetbedi  路  3Comments