I am working on a FastAPI project using Pydantic v2 and SQLAlchemy. I want to create a reusable mixin class that can be used to apply custom transformations to fields in Pydantic models. Specifically, I want to:
- Define a base class that performs custom operations on fields, such as transformations or logging.
- Use this base class as a mixin in various Pydantic models throughout my application.
Here’s a simplified version of what I am trying to achieve:
from pydantic import BaseModel
from typing import Dict, Any
class TranslatedBaseModel(BaseModel):
def model_dump(self, *args, **kwargs) -> Dict[str, Any]:
instance_dict = super().model_dump(*args, **kwargs)
print(instance_dict)
# Custom field transformation or logging
return instance_dict
class BlogOutputSchema(TranslatedBaseModel):
category: CategoryOutputSchema
translations: list[BlogTranslationOutpuSchema]
image: str
class Config:
from_attributes = True
json_loads = orjson.loads
json_dumps = orjson.dumps
@router.get("/", response_model=list[BlogOutputSchema])
async def get_projects(request: Request, db: Session = Depends(get_db)):
data = db.query(Blog).options(
joinedload(Blog.translations),
joinedload(Blog.category),
).filter(Blog.blog_status == "published")
blogs = [BlogOutputSchema.model_validate(blog) for blog in data]
return data.all()
Despite overriding model_dump(), it seems the method is not being invoked when I use Pydantic models. I expect the method to be called when converting the Pydantic model to a dictionary or JSON, but it is not showing the custom print statements.