SQL Alchemy ORM 获取器

0 投票
1 回答
1137 浏览
提问于 2025-04-16 09:25

我正在使用声明式风格来进行Sql Alchemy的映射。在我的表中,有一列会存储对象的一部分,格式是JSON。我有一个很好的方法来创建这个JSON,而我希望把它存储在我的数据库里。

我在我的类中把这个字段映射成一列,并尝试为它提供一个别名,但我发现这些别名只有在被其他代码使用时才会被调用。ORM(对象关系映射)从来不会访问这个获取方法。

我的问题是,我该如何告诉Sql Alchemy从一个方法中获取列的值呢?

以下是我的代码:

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

1 个回答

2

其实,使用 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)

撰写回答