如何将sqlalchemy hstore值转换为字符串?sqlalchemy + postgresql hstore到字符串
from sqlalchemy.dialects.postgresql import array, hstore
hs = hstore(array(['key1', 'key2', 'key3']), array(['value1', 'value2', 'value3']))
# this triggers sqlalchemy.exc.UnsupportedCompilationError
str(hs)
我希望像"key1"=>"value1", "key2"=>"value2", "key3"=>"value3"
我想用一个SQLAlchemy的API,而不是编写自定义字符串格式化函数近似我想要的。我正在使用一个使用sqlalchemy的遗留代码库:我需要保留任何内部的怪癖和格式化的转义逻辑。
但是,现有的代码库通过ORM表插入使用sqlalchemy,而我想直接将sqlalchemy hstore值转换为字符串?
UPDATE:我试图做这样的事情:
我有架构的现有表
create table my_table
(
id bigint default nextval('my_table_id_seq'::regclass),
ts timestamp default now(),
text_col_a text,
text_col_b text
);
我想下面的Python SQLAlchemy的代码工作:
str_value = some_function()
# Existing code is building an sqlalchemy hstore and inserting
# into a column of type `text`, not an `hstore` column.
# I want it to work with hstore text formatting
hstore_value = legacy_build_my_hstore()
# as is this triggers error:
# ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'hstore'
return db_connection.execute(
"""
insert into my_table(text_col_a, text_col_b) values (%s, %s)
returning id, ts
""",
(str_value, hstore_value).first()
编译错误是由于SQLA使用默认的话,您可以用明确反对编译PostgreSQL的话避免:'hs.compile(方言= postgresql.dialect())',但给你留下一个SQL表达式它拥有占位符(它应该),而不是转换为SQL的值。但是你的实际问题是什么?为什么你不能在Core插入中使用这个hstore构造(假设你是这样做的)?你想达到什么目的? –