Skip to content

Commit dbd0101

Browse files
author
John Lyu
committed
fix default value is InstrumentedAttribute in inherit
1 parent 0efd1bf commit dbd0101

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

sqlmodel/main.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -539,22 +539,24 @@ def __new__(
539539
config_kwargs = {
540540
key: kwargs[key] for key in kwargs.keys() & allowed_config_kwargs
541541
}
542-
new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
542+
base_fields = {}
543+
base_annotations = {}
544+
for base in bases[::-1]:
545+
if issubclass(base, BaseModel):
546+
base_fields.update(get_model_fields(base))
547+
base_annotations.update(base.__annotations__)
548+
# use base_fields overwriting the ones from the class for inherit
549+
# if base is a sqlalchemy model, it's attributes will be an InstrumentedAttribute
550+
# thus pydantic will use the value of the attribute as the default value
551+
dict_used["__annotations__"].update(base_annotations)
552+
new_cls = super().__new__(
553+
cls, name, bases, dict_used | base_fields, **config_kwargs
554+
)
543555
new_cls.__annotations__ = {
544556
**relationship_annotations,
545557
**pydantic_annotations,
546558
**new_cls.__annotations__,
547559
}
548-
# pydantic will set class attribute value inherited from parent as field
549-
# default value, reset it back
550-
base_fields = {}
551-
for base in bases[::-1]:
552-
if issubclass(base, BaseModel):
553-
base_fields.update(get_model_fields(base))
554-
fields = get_model_fields(new_cls)
555-
for k, v in fields.items():
556-
if isinstance(v.default, InstrumentedAttribute):
557-
fields[k] = base_fields.get(k, FieldInfo())
558560

559561
def get_config(name: str) -> Any:
560562
config_class_value = get_config_value(

0 commit comments

Comments
 (0)