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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With