如何将sqlalchemy值转换为字符串?
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,而不是编写一个与我想要的接近的自定义字符串格式函数。我正在使用使用sqlalchemy的遗留代码库:我需要保留任何内部怪癖和格式设置的转义逻辑。
但是,现有的代码库通过ORM表插入使用sqlalchemy,而我想直接将sqlalchemy值转换为字符串?
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()发布于 2017-08-31 21:44:47
让Postgresql为您执行强制转换,而不是尝试手动将hstore构造转换为字符串,SQLAlchemy处理转换到合适的文本表示形式:
return db_connection.execute(
my_table.insert().
values(text_col_a=str_value,
text_col_b=cast(hstore_value, Text)).
returning(my_table.c.id, my_table.c.ts)).first()如果列包含这样的内容,请尽快更改架构,使其使用hstore类型而不是文本。
https://stackoverflow.com/questions/45990100
复制相似问题