Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to modify Pydantic BaseModel attributes just after creating it?

I am starting to learn FastAPI and Pydantic and have a doubt. I have the following subclass of BaseModel

class Product(BaseModel):
  image: str
  name: str

After saving this model, I want image to store the value /static/ + image so as to create nice hyperlinked REST endpoint. This is possible using __post_init_post_parse__ hook of pydantic dataclass but since FastAPI currently doesn't support it, I was wondering what can be a workaround this.

like image 710
Shuvam Shah Avatar asked Oct 17 '25 06:10

Shuvam Shah


1 Answers

You could use a custom validator:

>>> from pydantic import BaseModel, validator
>>> class Product(BaseModel):
    image: str
    name: str
    @validator('image')
    def static_mage(cls, image):
        return '/static/{}'.format(image)


>>> p = Product(image='pic.png', name='product_1')
>>> p
Product(image='/static/pic.png', name='product_1')
like image 121
alex_noname Avatar answered Oct 18 '25 23:10

alex_noname