Replies: 2 comments
-
I read the source code, and found if One reason I'm attrachted by # source code
def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
data,
self_instance=self,
)
else:
sqlmodel_table_construct(
self_instance=self,
values=data,
)
# modified code
def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
raw_self = self.copy()
pydantic_validated_model = self.__pydantic_validator__.validate_python(
data,
self_instance=self,
)
if is_table_model_class(self.__class__):
sqlmodel_table_construct(
self_instance=raw_self,
values=pydantic_validated_model.model_dump(),
) In this way pydantic also works even though |
Beta Was this translation helpful? Give feedback.
-
Now I have fixed my code to pass tests def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
# old_dict = self.__dict__.copy()
# if not is_table_model_class(self.__class__):
# self.__pydantic_validator__.validate_python(
# data,
# self_instance=self,
# )
# else:
# sqlmodel_table_construct(
# self_instance=self,
# values=data,
# )
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
data,
self_instance=self,
)
else:
raw_self = deepcopy(self)
pydantic_validated_model = self.__pydantic_validator__.validate_python(
data,
self_instance=raw_self,
)
pydantic_dict = pydantic_validated_model.model_dump()
for k in pydantic_dict.keys():
if k not in data.keys():
continue
data[k] = pydantic_dict[k]
sqlmodel_table_construct(
self_instance=self,
values=data,
)
object.__setattr__(
self,
"__dict__",
{**old_dict, **self.__dict__},
) Not all tests passed, but tests do not pass also fails in original code, so I think my code works well. But for one test |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
Hi, I just found that althogh
SQLModel
derives frompydantic.BaseModel
, it doesn't really execute type checks in pydantic. Please read the code above. If we uncommenttest_pd()
and commenttest_sm()
, it would raise ValidationError sayingage
is not a valid integer; but if we executetest_sm()
, everything goes well, output would bealthough it should raise a ValidationError. And I found if I delete
table=True
, it behaves just likeBaseModel
, but in my conditiontable=True
must be set.I'd like to know why
pydantic
type checking doesn't work when I settable=True
? I have found some simillar discussions for example this but it remained unanswered. Is there a way to solve it?Operating System
Windows
Operating System Details
No response
SQLModel Version
0.0.21
Python Version
3.10.12
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions