🐛 Re-implement unreleased Pydantic utility

This commit is contained in:
Sebastián Ramírez 2021-08-24 16:01:22 +02:00
parent eb8c496e10
commit 46a6ed3d05

View File

@ -31,7 +31,7 @@ from pydantic.fields import FieldInfo as PydanticFieldInfo
from pydantic.fields import ModelField, Undefined, UndefinedType from pydantic.fields import ModelField, Undefined, UndefinedType
from pydantic.main import BaseConfig, ModelMetaclass, validate_model from pydantic.main import BaseConfig, ModelMetaclass, validate_model
from pydantic.typing import NoArgAnyCallable, resolve_annotations from pydantic.typing import NoArgAnyCallable, resolve_annotations
from pydantic.utils import ROOT_KEY, Representation, ValueItems from pydantic.utils import ROOT_KEY, Representation
from sqlalchemy import ( from sqlalchemy import (
Boolean, Boolean,
Column, Column,
@ -453,6 +453,12 @@ class_registry = weakref.WeakValueDictionary() # type: ignore
default_registry = registry() default_registry = registry()
def _value_items_is_true(v) -> bool:
# Re-implement Pydantic's ValueItems.is_true() as it hasn't been released as of
# the current latest, Pydantic 1.8.2
return v is True or v is ...
class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry): class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry):
# SQLAlchemy needs to set weakref(s), Pydantic will set the other slots values # SQLAlchemy needs to set weakref(s), Pydantic will set the other slots values
__slots__ = ("__weakref__",) __slots__ = ("__weakref__",)
@ -589,7 +595,7 @@ class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry
return cls(**value_as_dict) return cls(**value_as_dict)
# From Pydantic, override to only show keys from fields, omit SQLAlchemy attributes # From Pydantic, override to only show keys from fields, omit SQLAlchemy attributes
def _calculate_keys( def _calculate_keys( # type: ignore
self, self,
include: Optional[Mapping[Union[int, str], Any]], include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]], exclude: Optional[Mapping[Union[int, str], Any]],
@ -622,7 +628,7 @@ class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry
keys -= update.keys() keys -= update.keys()
if exclude: if exclude:
keys -= {k for k, v in exclude.items() if ValueItems.is_true(v)} keys -= {k for k, v in exclude.items() if _value_items_is_true(v)}
return keys return keys