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 between 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 sample:
chapter4_model_inheritance_01.py
from pydantic import BaseModel class PostCreate(BaseModel): title: str content: str class PostPublic(BaseModel): id: int title: str content: str class PostDB(BaseModel): id: int title: str content: str nb_views: int = 0