Postgresql 使用sqlalchemy,如何转换1&;0到postgres中的布尔值?
我在JSON中得到一些数据,其中布尔值为0和1 postgres表中有一个布尔字段,应为true和false 我在加载表时尝试以下操作:Postgresql 使用sqlalchemy,如何转换1&;0到postgres中的布尔值?,postgresql,sqlalchemy,Postgresql,Sqlalchemy,我在JSON中得到一些数据,其中布尔值为0和1 postgres表中有一个布尔字段,应为true和false 我在加载表时尝试以下操作: class PGBool(types.TypeDecorator): impl = types.BOOLEAN def process_result_value(self, value, dialect): #print value if value is not None: retur
class PGBool(types.TypeDecorator):
impl = types.BOOLEAN
def process_result_value(self, value, dialect):
#print value
if value is not None:
return bool(value)
return value
def listen(self, table, column_info):
type_ = column_info['type']
print column_info['name'], type_
if str(type_).split('.')[-1] == 'BOOLEAN':
column_info['type'] = PGBool
return column_info
def getTable(self, name):
return sq.Table(
name,
self.meta,
autoload=True,
autoload_with=self.con,
listeners=[
('column_reflect', listen)
]
)
def saveRecord(self, table, data):
..
..
if exist:
self.con.execute(
table.update().where(table.c.id == theGuid),
data
)
else:
self.con.execute(
table.insert(),
data
)
但是数据没有转换,仍然尝试插入0和1。当您使用
TypeDecorator
时,数据有两个方面需要考虑。一个是进入数据库的数据,另一个是出来的数据。输入端称为“绑定参数”,输出端称为“结果”数据。因为您希望在这里处理插入,所以您处于绑定端,因此TypeDecorator看起来像:
from sqlalchemy.types import TypeDecorator, Boolean
class CoerceToBool(TypeDecorator):
impl = Boolean
def process_bind_param(self, value, dialect):
if value is not None:
value = bool(value)
return value