-
First Check
Commit to Help
Example CodeDescriptioni was creating a Sqlmodel to conncect with postgres. |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
|
How we approach when using json type in sqlmodel |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
|
iam closing it , i have to check on it again. |
Beta Was this translation helpful? Give feedback.
-
|
Iam posting this to avoid the same mistake by other created_on: datetime =Column(
DateTime(timezone=True),
server_default=func.now()
)
updated_on: datetime = Column(
DateTime(timezone=True),
server_default=func.now(),
server_onupdate=func.now()
)corrected code is as follows created_on: datetime = Field(sa_column=Column(
DateTime(timezone=True),
server_default=func.now()
))
updated_on: datetime = Field(sa_column=Column(
DateTime(timezone=True),
server_default=func.now(),
server_onupdate=func.now()
)) |
Beta Was this translation helpful? Give feedback.
-
|
use this instead "Here's how to define a JSON field in SQLModel: Define the field with sa_column: In your SQLModel class, define the field that will store JSON data and specify its SQLAlchemy column type using sa_column=Column(JSON). |
Beta Was this translation helpful? Give feedback.
-
|
Hi everyone I suggest to have a global variable like I have done this by monkey patching import sqlmodel.main
from typing import Union, Annotated
from pydantic import JsonValue as PydanticJsonValue
from pydantic.types import Json as PydanticJson
from sqlalchemy.types import JSON as SQLAlchemyJSON
# I use pascal case for constants
TypeAnnotationMap = {
PydanticJson: SQLAlchemyJSON,
PydanticJsonValue: SQLAlchemyJSON
}
_gst = sqlmodel.main.get_sqlalchemy_type
def get_sqlalchemy_type(field: Any) -> Any:
try:
return _gst(field)
except Exception as exc:
type_ = None
if hasattr(field, 'type_'):
type_ = field.type_
elif field.annotation:
type_ = field.annotation
if (
get_origin(type_) is Union
and len(type_.__args__) == 2
and type(None) in type_.__args__
):
type_ = next(arg for arg in type_.__args__ if arg is not None)
if get_origin(type_) is Annotated:
type_ = type(type_.__metadata__[0])
if type_ in TypeAnnotationMap.keys():
return TypeAnnotationMap[type_]
raise exc
sqlmodel.main.get_sqlalchemy_type = get_sqlalchemy_type |
Beta Was this translation helpful? Give feedback.
Iam posting this to avoid the same mistake by other
The issue was in another line of code, where i missed the Field
corrected code is as follows