【问题标题】:SQL Alchemy ORM GetterSQLAlchemy ORM 获取器
【发布时间】:2011-06-03 16:46:54
【问题描述】:

我正在为 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

【问题讨论】:

    标签: python properties sqlalchemy getter


    【解决方案1】:

    使用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)
    

    【讨论】:

    • 我会将此作为正确答案,但就我而言,我需要在插入/更新之前和填充之后访问整个实体。不知何故,我错过了 Mapper Events,这让我明白了这一点。 sqlalchemy.org/docs/orm/interfaces.html
    猜你喜欢
    • 2021-02-06
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2018-03-24
    • 2020-05-21
    • 2017-02-26
    • 2013-10-16
    • 1970-01-01
    相关资源
    最近更新 更多