【问题标题】:Python list to PostgreSQL HSTORE via SQLAlchemy通过 SQLAlchemy 到 PostgreSQL HSTORE 的 Python 列表
【发布时间】:2021-12-03 11:59:16
【问题描述】:

我想使用 SQLAlchemy 将包含列表的 Python 字典作为 HSTORE 对象存储在 PostgreSQL 数据库中。跟随我的餐桌课。

from sqlalchemy.dialects.postgresql import HSTORE
from sqlalchemy import Column, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Data(Base):
    id = Column(String, primary_key=True)
    data = Column(HSTORE)

我在以下事项中插入我的项目。

data = Data(
    id='fancy_id',
    data={
        'foo': ['bar', 'bar']
    },
)

db.Session.add(scan)
db.Session.commit()

这会导致 ROLLBACK 发生并引发以下异常。

sqlalchemy.exc.DataError: (psycopg2.errors.ArraySubscriptError) wrong number of array subscripts

[SQL: INSERT INTO data (id, data) VALUES (%(id)s, %(data)s)]
[parameters: {'id': 'fancy_id', 'data': {'foo': ['bar', 'bar']}}]

但是,插入可以在没有列表的情况下进行。

data = Data(
    id='fancy_id',
    data={
        'foo': 'bar'
    },
)

我关注了PostgreSQL SQLAlchemy 1.4 documentation,但没有发现表明此限制的注释。我错过了什么吗?如何通过 SQLAlchemy 将 Python 列表存储在 PostgreSQL HSTORE 对象中?

提前致谢。

【问题讨论】:

    标签: python postgresql sqlalchemy psycopg2 hstore


    【解决方案1】:

    老实说,json/jsonb 会是更好的选择。然后,您可以将带有列表的 Python dict 直接映射到带有数组的 JSON 对象。如果你想使用hstore 那么:

    create table hstore_test(id int, hs_fld hstore);
    insert into hstore_test values (1, 'a=>1');
    insert into hstore_test values (1, 'b=>"[1,2]"'::hstore);
    select * from hstore_test ;
     id |    hs_fld    
    ----+--------------
      1 | "a"=>"1"
      1 | "b"=>"[1,2]"
    
    --So for your example
    
    data={
            'foo': "['bar', 'bar']"
        },
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 2021-10-24
      • 2022-08-24
      相关资源
      最近更新 更多