Using a custom JSON encoder for SQLAlchemy's PostgreSQL JSONB implementation

前端 未结 4 1687
遥遥无期
遥遥无期 2020-12-17 17:24

I am using SQLAlchemy\'s core library to access some PostgreSQL database. Consider I have the following table:

create table foo (j jsonb);

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 17:47

    This is supported via the json_serializer keyword argument to create_engine, as documented under sqlalchemy.dialects.postgresql.JSON:

    def _default(val):
        if isinstance(val, Decimal):
            return str(val)
        raise TypeError()
    
    def dumps(d):
        return json.dumps(d, default=_default)
    
    engine = create_engine(..., json_serializer=dumps)
    

提交回复
热议问题