0

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

  • What is the goal of using `create_model` inside your classes? What are you trying to achieve that `Optional[StatsOptional]` doesn't do? – MatsLindh Nov 11 '21 at 14:14
  • Remember to avoid posting code, data or error messages as images. See [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Hernán Alarcón Nov 15 '21 at 02:57
  • I was trying to make the process-info as optional, but in the previous commit i used all these fields in one single create model, but i need to do distinguish that process_info field as sub-optional, thus was create_model at that time, now it is removed by using an optional[dict]. @MatsLindh – Abhishek Ratnam Nov 16 '21 at 07:22
  • Will follow up the guidelines :) @HernánAlarcón – Abhishek Ratnam Nov 16 '21 at 07:23
  • @AbhishekRatnam did you check my answer below? – floatingpurr Nov 16 '21 at 08:35

1 Answers1

0

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
floatingpurr
  • 7,749
  • 9
  • 46
  • 106