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.
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!
Most helpful comment
Hi @RamiAwar and happy new year!
By default a
BaseModelwill ignore extra fields. You can have a look at the config doc with theextraparameter.So you can directly do