pythoninheritancepydantic

Inherit only a Subset of Fields of Pydantic Model


I would like to generate a Pydantic model that inherits from a parent class, but only has a subset of that parent model's fields.

E.g. ModelB should inherit only field_b from ModelA:

from pydantic import BaseModel

class ModelA(BaseModel):
    field_a: str
    field_b: str

class ModelB(ModelA):
    pass

Solution

  • It was enough for me to hard copy the field and to adjust the extras I had defined. Here is a snippet from my code:

    import copy
    
    from pydantic import BaseModel
    
    
    def copy_primary_field(
            model_from: BaseModel,
            model_to: BaseModel,
            primary_key: str,
    ) -> BaseModel:
        new_field_name = f"{model_from.__name__}" + "_" + primary_key
        model_to.__fields__[new_field_name] = copy.deepcopy(
            model_from.__fields__[primary_key]
        )
        model_to.__fields__[new_field_name].name = new_field_name
        model_to.__fields__[new_field_name].field_info.extra["references"] = (
                f"{model_from.__name__}" + ":" + primary_key
        )
    
        return model_to