salius
salius

Reputation: 1088

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

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

Upvotes: 12

Views: 13643

Answers (2)

FN_
FN_

Reputation: 853

I have come across the same issue, but the given solution did not work for me. I have figured out that Pydantic made some updates and when using Pydantic V2, you should allow extra using the following syntax, it should work

import pydantic
from pydantic import BaseModel , ConfigDict


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

    model_config = ConfigDict(extra='allow')

https://docs.pydantic.dev/latest/concepts/models/#extra-fields

Upvotes: 0

NobbyNobbs
NobbyNobbs

Reputation: 1434

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

Upvotes: 20

Related Questions