简体   繁体   English

通过 SQLAlchemy 到 PostgreSQL HSTORE 的 Python 列表

[英]Python list to PostgreSQL HSTORE via SQLAlchemy

I'd like to store Python dicts containing lists as HSTORE object in a PostgreSQL database using SQLAlchemy.我想使用 SQLAlchemy 将包含列表的 Python 字典作为 HSTORE 对象存储在 PostgreSQL 数据库中。 Following my table class.跟随我的餐桌课。

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)

I insert my items in the following matter.我在以下事项中插入我的项目。

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

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

This causes a ROLLBACK to happen and the following exception raises.这会导致发生 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']}}]

However, the insertion works without the list.但是,插入可以在没有列表的情况下工作。

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

I followed the PostgreSQL SQLAlchemy 1.4 documentation and can't spot a note indicating this limitation.我遵循了PostgreSQL SQLAlchemy 1.4 文档,但找不到说明此限制的注释。 Am I missing something?我错过了什么吗? How can I store Python lists inside PostgreSQL HSTORE objects via SQLAlchemy?如何通过 SQLAlchemy 在 PostgreSQL HSTORE 对象中存储 Python 列表?

Thanks in advance.提前致谢。

Honestly for this sort of thing json/jsonb would be a better option.老实说,对于这类事情json/jsonb将是更好的选择。 Then you would have a direct mapping of Python dict with list to JSON object with array.然后,您将直接将带有列表的 Python dict 映射到带有数组的 JSON 对象。 If you want to use hstore then:如果你想使用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']"
    },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM