Hi Sourabh,
I do have another question for you. I'd like you to shed light on the usage of attribute orm_mode=True
within sublass Config
of class ShowBlog
. Leaving aside the fact that Pydantic v2 has discarded orm_mode
in favour of something else, my question is, why do we have to set it considering that in the codebase we are never explicitly transforming SQLAlchemy objects into Pydantic objects?
Indeed, my understanding is that it is needed to provide such transformation given that FastAPI is designed to work with Pydantic objects.
Explicitly we are not transforming in the code but behind the scenes, it is needed. For instance, consider this code:
@router.get("/blog/{id}", response_model=ShowBlog)
def get_blog(id: int, db: Session = Depends(get_db)):
blog = retreive_blog(id=id, db=db)
return blog
Notice the response_model=ShowBlog
Normally, pydantic expects json as input. But in this case, we are sending a SQLAlchemy model object as a Json response. To parse this, we have to tell Pydantic that the input will be a orm object and the output will be JSON.
Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.
We know, we might make it hard for you but definitely worth the efforts.
© Copyright 2022-23 Team FastAPITutorial