首页 > 解决方案 > sqlalchemy-sqlite 数据库当前(01/2018)是否与 JSON 对象直接兼容?

问题描述

我目前正在尝试创建一个包含 JSON 对象列的数据库:

import sqlalchemy as sql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy import create_engine
from sqlalchemy.types import JSON

# Creating the Base Object for the tables.
Base = declarative_base()

class Observations(Base):
    # Declaring the tablename.
    __tablename__='observations'

    # Defining the PK column.
    OBS_id=sql.Column(sql.Integer, primary_key=True)

    # Defining a FK column to stabilishes the connection between this table
    # and the ActiveRegion table.
    ar_id=sql.Column(sql.Integer, sql.ForeignKey(ActiveRegion.AR_id))

    # Creating a column to store the sharp metadata as a json object.
    hmi_meta_data = sql.Column('hmimetadata', JSON, nullable=False)

但是,当我运行代码来构建数据库时,我得到一个CompileError说:

CompileError: (in table 'observations', column 'hmimetadata'): Compiler <sqlalchemy.dialects.sqlite.base.SQLiteTypeCompiler object at 0x1c1e2b45f8> can't render element of type <class 'sqlalchemy.sql.sqltypes.JSON'>

我已经在 SO 上找到了一些解决方法来实现一个带有 JSON 对象的列,但是由于这个问题是不久前被问到的,我想知道是否有一个本机支持可以消除这种实现的需求。

根据 sqlalchemy types文档,JSON 类型应该适用于具有实际 JSON 类型的 SQL 后端,其中包括版本 3.9 的 SQLite。我正在检查我的 3.26 版本,它是最后一个版本(sqlite 发布网站)。那么这是未来 sqlalchemy 版本的里程碑吗?或者还有什么我没有考虑的吗?

谢谢。

标签: pythonjsonsqlitesqlalchemy

解决方案


正如评论中指出的,sqlalchemy 在 1.3 版中支持 JSON,可以在此处下载,目前是 beta 版。新版本的文档以及1.2 版的变更日志已经可用。


推荐阅读