Python SQL炼金术
我正在使用Sql Alchemy映射的声明式样式。我的表中有一列将对象的部分存储为JSON。我有一个很好的方法负责创建JSON,这就是我想要存储在数据库中的内容 我已将类中的字段映射为列,并尝试为其提供同义词,但发现这些字段只能通过使用代码来调用。ORM从不访问getter 我的问题是,如何让SA从方法中获取列的值 我的代码是这样的:Python SQL炼金术,python,properties,sqlalchemy,getter,Python,Properties,Sqlalchemy,Getter,我正在使用Sql Alchemy映射的声明式样式。我的表中有一列将对象的部分存储为JSON。我有一个很好的方法负责创建JSON,这就是我想要存储在数据库中的内容 我已将类中的字段映射为列,并尝试为其提供同义词,但发现这些字段只能通过使用代码来调用。ORM从不访问getter 我的问题是,如何让SA从方法中获取列的值 我的代码是这样的: class JsonProperty(object): _value = None def __get__(self, instance, ow
class JsonProperty(object):
_value = None
def __get__(self, instance, owner):
if instance is None:
return self
return self._value
def __set__(self, instance, value):
self._value = value
class TableTestParent(Base,object):
__tablename__ = 'Test'
id = Column(Integer, primary_key=True)
age = Column(Integer)
name = Column(String)
_model = Column('model',String)
@synonym_for('_model')
@property
def model(self):
return self._modelToJson()
def _modelToJson(self):
dict = {}
for item in self.__class__.__dict__.iteritems():
if type(item[1]) is JsonProperty:
attName = item[0]
attValue = getattr(self,attName,'')
dict[attName] = attValue
return json.dumps(dict)
class TableTest(TableTestParent):
email = JsonProperty()
phone = JsonProperty()
bestTimes = JsonProperty()
obj = TableTest()
obj.email = 'e@mail.com'
obj.name = 'Yeroc'
#save to db
当使用
TypeDecorator
时,实际上很容易创建这样的自定义类型:
然而。。。如果您没有任何特定依赖于json的内容,我建议您使用PickleType
而不是自定义json类型:
下面是一个如何使json列正常工作的示例:
class JsonType(types.TypeDecorator):
impl = types.Unicode
def process_bind_param(self, value, dialect):
return json.dumps(value)
def process_result_value(self, value, dialect):
return json.loads(value)
我将保留这一正确答案,但在我的情况下,我需要在插入/更新之前和填充之后访问整个实体。不知怎的,我错过了Mapper事件,这让我很失望。