team23 / pydantic-partial

Create partial models from pydantic models
MIT License
51 stars 8 forks source link

question #5

Closed phifuh closed 1 year ago

phifuh commented 1 year ago

Hey thanks for sharing this project.

I am right now searching for some good way on how to implement a patch approch. We have a huge datamodel with about 500variables and a tone of nested classes. If I understand it correct I would manually need to setup all the recursive nested classes? Is there a smarter way? For big models it might be to complex

ddanier commented 1 year ago

Hope you have found the recursive option: https://github.com/team23/pydantic-partial#recursive-partials

phifuh commented 1 year ago

Hope you have found the recursive option: https://github.com/team23/pydantic-partial#recursive-partials

Yes I saw that but if I understand it correctly It would still mean that I have to define a lot of them manual which wouldnt be a good solution for any big data model.

This might be a better solution for my specific usecase: https://stackoverflow.com/a/71135795 class UserOptional(UserCreate): __annotations__ = {k: Optional[v] for k, v in UserCreate.__annotations__.items()}

I havent tested it tho

ddanier commented 1 year ago

If you pass recursive=True to your uppermost model it will automatically create the sub models as partials, too. (pydantic uses "recursive models" as a name for sub models, see https://docs.pydantic.dev/usage/models/#recursive-models)

If you take the example from the docs:

class InnerSomething(PartialModelMixin, pydantic.BaseModel):
    name: str

class OuterSomething(pydantic.BaseModel):
    name: str
    things: List[InnerSomething]

# Create a full partial model
RecursiveOuterSomethingPartial = create_partial_model(OuterSomething, recursive=True)

This will automatically create a model InnerSomethingPartial which will be a partial representation of InnerSomething. So you don't need to actually define this model manually. Anyways I still would recommend doing so, to be able to use this model throughout your code - but thats your decision. ;-)