11

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))

salius
  • 918
  • 1
  • 14
  • 30

1 Answers1

17

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

NobbyNobbs
  • 1,341
  • 1
  • 11
  • 17