更新时间:2022-11-28 18:07:20
如果需要使用 native'xml'数据类型在Postgresql数据库中,您需要编写自 UserDefinedType 而不是从TypeDecorator继承的自定义类型。 文档
If you need to have native 'xml' data type in postgresql database, you need to write custom type which inherited from UserDefinedType not from TypeDecorator. Documentation
这是我在其中一个项目中使用的:
Here is what I used in one of the projects:
import xml.etree.ElementTree as etree
import sqlalchemy
class XMLType(sqlalchemy.types.UserDefinedType):
def get_col_spec(self):
return 'XML'
def bind_processor(self, dialect):
def process(value):
if value is not None:
if isinstance(value, str):
return value
else:
return etree.tostring(value)
else:
return None
return process
def result_processor(self, dialect, coltype):
def process(value):
if value is not None:
value = etree.fromstring(value)
return value
return process