sqlmodel icon indicating copy to clipboard operation
sqlmodel copied to clipboard

✨ Automatically map dictionaries to JSON

Open patrick91 opened this issue 2 months ago • 5 comments

patrick91 avatar Oct 09 '25 14:10 patrick91

@YuriiMotov happy for you to add support for TypeDecorator, maybe we can ask @tiangolo if he has any opinions first? 😊

patrick91 avatar Oct 30 '25 10:10 patrick91

@YuriiMotov also doesn't seems like SQLModel does validation for any incoming data? it would be a different behaviour from the rest?

patrick91 avatar Oct 30 '25 12:10 patrick91

@YuriiMotov also doesn't seems like SQLModel does validation for any incoming data? it would be a different behaviour from the rest?

It's true, but.. Currently, in most cases we will have validation on DB side (since we specify the types of columns and other constraints). So, assuming DB schema is in line with models, we don't need to validate it on SQLModel side (assuming we are using not SQLite, but more advanced DB). Having Dict -> JSON mapper by default will increase the number of cases when data is not validated by any side..

YuriiMotov avatar Oct 30 '25 13:10 YuriiMotov

As an idea: we can add such validation for dict - JSON mapping, but document how it can be disabled. So, it will be enabled by default, but if it's not needed in particular project, developers will be able to disable it and avoid overheads.

For example

class MyModel(SQLModel, table=True):
    f1: dict[str, int]  # DB data will be validated
    f2: dict[str, int] = Field(sa_type=JSON)  # DB data will not be validated

YuriiMotov avatar Nov 03 '25 09:11 YuriiMotov

convert data to JSON, but also ensure data has valid type

I've had good luck using Pydantic's TypeAdapter in type decorators for this; it would let you support Pydantic types as well as builtins like Dict[str, int].

nkrishnaswami avatar Nov 03 '25 22:11 nkrishnaswami