我对Sql Alchemy映射使用声明性样式。我的表上有一个列,它将把对象的一部分存储为JSON。我有一个很好的方法,负责创建JSON,这就是我想要存储在数据库中的东西。
我已经将类中的字段映射为一个列,并尝试为其提供一个同义词,但我发现只有通过使用代码才能调用这些同义词。ORM从不访问getter。
我的问题是,如何告诉SA从方法中获取列的值?
下面是我的代码:
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发布于 2011-01-05 08:02:14
在使用TypeDecorator:http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/types.html#sqlalchemy.types.TypeDecorator时,创建这样的自定义类型实际上非常容易
然而..。如果您没有任何专门依赖于json的东西,我建议您使用PickleType而不是自定义的json类型:http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/types.html#sqlalchemy.types.PickleType
下面是一个关于如何让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)https://stackoverflow.com/questions/4599060
复制相似问题