SQLModel + Pydantic v1 vs SQLModel + Pydantic v2 - different assignment behaviour #824
-
First Check
Commit to Help
Example Codefrom pydantic import BaseModel
from sqlmodel import SQLModel, Field
from datetime import date
from typing import Optional
class A(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
dob: date
class B(BaseModel):
dob: date
a=A(dob='1980-01-01')
print(a)
b=B(dob='1980-01-01')
print(b) DescriptionThe code above prints
if executed with pydantic v1 in the mix (1)*. But it prints
With pydantic v2 in the mix (2)*. This behaviour essentially breaks a fastapi application I am migrating to pedantic v2, because I assume, for example, that date attributes within objects passed in the body of post methods are already converted (originally passed as strings). I couldn't find any recommendation related to this. I realize I could set table=False on the SQLModel object, but if I do that other behaviours change, related to validations for example. Am I missing something? (1) pyproject dependencies
(2) pyproject deps
Operating SystemLinux Operating System DetailsNo response SQLModel Version0.0.16 Python Version3.10 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
note: adding
to my models is not really an option, because that will make the code also start validating objects as soon as they are created, not allowing different attributes to be populated in phases (which is something I suspect a lot of people do frequently) |
Beta Was this translation helpful? Give feedback.
-
Is your issue about the fact that in Pydantic v2, the |
Beta Was this translation helpful? Give feedback.
-
Any updates or thoughts on this one? |
Beta Was this translation helpful? Give feedback.
-
SQLModels with Create from sqlmodel import SQLModel, Field
from datetime import date
from typing import Optional
class ABase(SQLModel):
id: Optional[int] = Field(default=None, primary_key=True)
dob: date
class A(ABase, table=True):
pass
a = ABase(dob="1980-01-01")
print(a) # id=None dob=datetime.date(1980, 1, 1) |
Beta Was this translation helpful? Give feedback.
SQLModels with
table=True
bypass validation, you shouldn't use models withtable=True
for input validation.Create
ABase
model, move common fields there and use it for validation: