Pydantic model with data type field. Can't use Union, Optional, List

Viewed 1141

I'm using pydantic in my project and defined a model with Type field.

from typing import Type, Union
from pydantic import BaseModel

class Item(BaseModel):
    data_type: Type

Works well with standard library types (bool, int, str etc), but when I try to create an instance using for example Union, Optional or List from typing module:

it = Item(data_type=Union[int, str])

I get an error:

File "pydantic/main.py", line 362, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for Item
data_type
  a class is expected (type=type_error.class)

How can I define data_type field for Union, Optional and List types?

0 Answers
Related