pydantic Model Inheritance workaround to retyping information?

Question:

I have a model_B that inherits from model_A as seen below:

class model_A(BaseModel):
    Name: str
    Age: int
    phone: int

class model_B(model_A):
    email: str
    location: str

When using my models in code is there a way I can create a model_B without having to retype all the information from model_A? Instead of doing the below is there a way to just add in the email and location and keep all other attributes from model_A?

A = model_A(
    Name = "Jon"
    Age = 20
    phone = 123
    
)

B = model_B(
    Name = "Jon"
    Age = 20
    phone = 123
    email = "test@123"
    location = "Earth"
)
Asked By: Masterstack8080

||

Answers:

One solution:

A = model_A(
    Name = "Jon"
    Age = 20
    phone = 123
    
)

B = model_B(
    email = "test@123",
    location = "Earth",
    **A.dict()
)

to exclude Age:

B = model_B(
    email = "test@123",
    location = "Earth",
    **A.dict(exclude={'Age'})
)
Answered By: Waket Zheng
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.