The new version of SQLAlchemy introduced the ability to use type annotations using Mapped[Type] (link).
My question is, what should we use as an annotation for sqlalchemy.types.JSON
? Is just dict
will be ok?
I'm just using dict, but I want to understand the correct option for this.
You will need to first declare a mapping in your DeclarativeBase Type Annotation Map like this:
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.types import JSON
from typing import Any
class Base(DeclarativeBase):
type_annotation_map = {
dict[str, Any]: JSON
}
See the docs on type_annotation_map
for more information.
Note: This will also work for database specific json dialects, eg Postgres' JSONB
type. For older versions of Python, you may need to do from typing import Dict
and use that instead of using dict
directly.
After doing so, you can use the above datatype in your table as so:
from sqlalchemy.orm import Mapped
class YourTable(Base):
your_column: Mapped[dict[str, Any]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With