Search code examples
pythonpython-3.xpydanticpydantic-v2

How to properly annotate pydantic fields if it's another class


I have a model with the fields which are other Pydantic models (but not instances of them), so I'm able to use it later as a builder.

class ItemModel(BaseModel):
    id: int

class UserModel(BaseModel):
    name: str

class MatchModels(BaseModel):
    name: str
    user_model: Optional[type(BaseModel)] = None
    item_model: Optional[type(BaseModel)] = None


m = MatchModels(
    name="match only user",
    user_model=UserModel,
)

Is it correct to use type(BaseModel) here if I want to instantiate it later somewhere in the code? What is the proper type annotation would be here?


Solution

  • pyright suggest to annotate like this

    from typing import Optional, Type
    
    class MatchModels(BaseModel):
        name: str
        user_model: Optional[Type[BaseModel] = None
        item_model: Optional[Type[BaseModel]] = None