wd-smebiz/utils/pydantic_utils.py

21 lines
811 B
Python
Raw Normal View History

from pydantic import BaseModel
2023-08-02 14:24:28 +08:00
from typing import Optional
2023-08-02 18:32:22 +08:00
class AllOptional(type(BaseModel)):
2023-08-02 14:24:28 +08:00
def __new__(cls, name, bases, namespaces, **kwargs):
annotations = namespaces.get('__annotations__', {})
for base in bases:
annotations.update(getattr(base, '__annotations__', {}))
2023-08-02 14:24:28 +08:00
for field in annotations:
if not field.startswith('__'):
annotations[field] = Optional[annotations[field]]
namespaces['__annotations__'] = annotations
# Set default values
for field in annotations:
if not field.startswith('__') and field not in namespaces:
namespaces[field] = None # set default value to None only if it's not already set
2023-08-02 14:24:28 +08:00
return super().__new__(cls, name, bases, namespaces, **kwargs)