Pydantic add field to model after a model validation (add filed to incoming model)

Viewed 3382

I have an incoming pydantic User model. To add field after validation I'm converting it to dict and adding a field like for a regular dict.

user = employee.dict()
user.update({'invited_by': 'some_id'})
db.save(user)

Is there a shorter AND CLEANEST way to add a field? Because even for myself it's no such clear, every time that I meeting this code (that wrote by myself) I thinking "Why I'm converting model to dict as separate instruction/line if I can do it inside save function (db.save(user))

1 Answers

If you have access to model definition, you could allow extra fields in the model Config.

import pydantic
from pydantic import Extra


class A(pydantic.BaseModel):
    a: str = "qwer"

    class Config:
        extra = Extra.allow

a = A()
a.b = 1234
print(a)  # a = 'qwer' b = 1234

Related