Closed HonQii closed 6 months ago
@HonQii For this requirement I would use a completely different approach. Defining some parts of the model using separate model classes and then using class inheritance (remember: in Python you can have multiple parents) to construct the full model. See this as an example:
class ModelPart1(pydantic.BaseModel):
part1_foo: str
class ModelPart2(pydantic.BaseModel):
part2_foo: str
class ModelPart3(pydantic.BaseModel):
part3_foo: str
class TheFullModel(ModelPart1, ModelPart2, ModelPart3):
pass
You may then combine this with partial models of course 😉
Like for example having all the fields from ModelPart2
optional:
class TheFullModel(
ModelPart1,
create_partial_model(ModelPart2),
ModelPart3,
):
pass
Also note: If you are using FastAPI you can remove the None
values (due to fields being partial) from the response data by using response_model_exclude_none=True
on the endpoint. See https://fastapi.tiangolo.com/tutorial/response-model/?h=response_model_exclude#response-model-encoding-parameters
Does this solve your issue?
For this requirement I would use a completely different approach. Defining some parts of the model using separate model classes and then using class inheritance (remember: in Python you can have multiple parents) to construct the full model. See this as an example:
I'll try it. Thank you.
Hello, this is a great project, thank you for sharing it, it perfectly accomplishes what I want to do. However, I have a scenario now where I have a base Model with all properties, and I want to convert it into multiple child models with only some properties using 'partial', but currently, I can only make the unnecessary properties optional. It would be perfect if I could completely remove properties in the child models.