Creating model variations with class inheritance
In Chapter 3, Developing a RESTful API with FastAPI, we saw a case where we needed to define two variations of a Pydantic model in order to split the data we want to store in the backend and the data we want to show to the user. This is a common pattern in FastAPI: you define one model for creation, one for the response, and one for the data to store in the database.
We show this basic approach in the following example:
chapter04_model_inheritance_01.py
from pydantic import BaseModelclass PostCreate(BaseModel): title: str content: str class PostRead(BaseModel): id: int title: str content: str class Post(BaseModel): id: int title: str content: str nb_views: int = 0