Skip to content

Commit c1dff79

Browse files
author
John Lyu
committed
disable pydantic warning during polymorphic
1 parent 95c6a1e commit c1dff79

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

sqlmodel/main.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import ipaddress
22
import uuid
3+
import warnings
34
import weakref
45
from datetime import date, datetime, time, timedelta
56
from decimal import Decimal
@@ -539,21 +540,33 @@ def __new__(
539540
config_kwargs = {
540541
key: kwargs[key] for key in kwargs.keys() & allowed_config_kwargs
541542
}
543+
is_polymorphic = False
542544
if IS_PYDANTIC_V2:
543545
base_fields = {}
544546
base_annotations = {}
545547
for base in bases[::-1]:
546548
if issubclass(base, BaseModel):
547549
base_fields.update(get_model_fields(base))
548550
base_annotations.update(base.__annotations__)
551+
if hasattr(base, "__tablename__"):
552+
is_polymorphic = True
549553
# use base_fields overwriting the ones from the class for inherit
550554
# if base is a sqlalchemy model, it's attributes will be an InstrumentedAttribute
551555
# thus pydantic will use the value of the attribute as the default value
552556
base_annotations.update(dict_used["__annotations__"])
553557
dict_used["__annotations__"] = base_annotations
554558
base_fields.update(dict_used)
555559
dict_used = base_fields
556-
new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
560+
# if is_polymorphic, disable pydantic `shadows an attribute` warning
561+
if is_polymorphic:
562+
with warnings.catch_warnings():
563+
warnings.filterwarnings(
564+
"ignore",
565+
message="Field name .+ shadows an attribute in parent.+",
566+
)
567+
new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
568+
else:
569+
new_cls = super().__new__(cls, name, bases, dict_used, **config_kwargs)
557570
new_cls.__annotations__ = {
558571
**relationship_annotations,
559572
**pydantic_annotations,

0 commit comments

Comments
 (0)