Search code examples
python-3.xmodeloption-typefastapipydantic

How shall i define create sub-optional models in Optional[] working with typing and pydantic libs for FastAPI python?


Hi i'm a beginer in FastAPi, getting this error as

TypeError: typing.Union[pydantic.main.stats, NoneType] is not a generic class.

How shall i create sub-optional models? these are my imports.

from typing import Optional,List
from pydantic import BaseModel, create_model

enter image description here enter image description here


Solution

  • You can just use an optional nested model, as described in the doc

    from typing import Optional, Set
    
    from fastapi import FastAPI
    from pydantic import BaseModel
    
    app = FastAPI()
    
    
    class Image(BaseModel):
        url: str
        name: str
    
    
    class Item(BaseModel):
        name: str
        description: Optional[str] = None
        price: float
        tax: Optional[float] = None
        tags: Set[str] = []
        image: Optional[Image] = None
    
    
    # do your stuff