Search code examples
modelfastapipydantic

Common fields for different fastapi models in one place using pydantic models


I am using fastapi framework and creating models using Pydantic.I have a 2 models customerProfileShort and CustomerProfileLong .Among these models 6 fields are common .Is there is a way we can define the fileds at oneplace and reuse them in any of the models.

define them at one place like this

address: Optional[str] = Field(example="4849 William Terrace")

use the same in different models

I have to do in this way ?? or any simpler way ??

class First_name(BaseModel):
    first_name: str = Field(None, example="John")
class Last_name(BaseModel):
    last_name: str = Field(None, example="Doe")
class Actions_Count(BaseModel):
    actions_count: int = Field(None, example=131)
class Event_performed(BaseModel)
    action_name: str Field(None, example="check out")
class Address(BaseModel):
    address: Optional[str] = Field(example="4849 William Terrace")
class State(BaseModel):
    state: Optional[str] = Field(example="NC")
class Country(BaseModel):
    country: Optional[str] = Field(example="US")
    
class ShortCustomerProfile(Address,Actions_Count,Last_name,First_name):
        pass

Class State_Counts(State,Country):
        pass

class Events_Performed_By_Customer(First_name,Last_name,Event_performed):
        pass

I am using fastapi framework and creating models using Pydantic.I have a 2 models customerProfileShort and CustomerProfileLong .Among these models 6 fields are common .Is there is a way we can define the fileds at oneplace and reuse them in any of the models.

define them at one place like this

address: Optional[str] = Field(example="4849 William Terrace")

use the same in different models


Solution

  • Pydantic supports inheritance in the same as way as any other Python classes. It's also given as an example in the FastAPI docs. You can do this by creating a base model that you then inherit from (and you can do this in as many layers as required, but be careful to not make the code incomprehensible).

    class CustomerProfileShort:
        address: Optional[str] = Field(example="4849 William Terrace")
    
    
    class CustomerProfileLong(CustomerProfileShort):
        more_information: str
    

    Python also supports multiple inheritance so you can "compose" a resulting model from many other, smaller models based on what they should support. But again, be careful not to overdo it, as that will just makes your code harder to follow and understand.