sqlalchemy如何使用自定义类作为属性 [英] How can sqlalchemy work with custom class as the attributes

查看:266
本文介绍了sqlalchemy如何使用自定义类作为属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sqlalchemy和flask-sqlalchemy,我的数据库模型之一带有状态列

I am using sqlalchemy and flask-sqlalchemy, one of my db model comes with a state column

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(8))
    state = db.Column(db.Integer, default=ServerState.IN_PACKAGE, nullable=True)

    def init_state(self):

        self.state = State1

    def transit_state(self):

        self.state.next(self) 

问题在于此状态列以整数形式保存到db中,但是为了实现适当的状态机,它被实现为Class:

The problem is that this state column is saved into db as a integer, but in order to implement a proper state machine, it is implemented as a Class:

class State1(BaseState):

    __int = 100
    __name = 'State1'

    @staticmethod
    def next(item):
        if item.contidition1 is None or item.condition2 is None:
            raise InvalidStateTransition

        item.state = State2

这很好并且可以使代码保持干净,但是关键的问题是,当我想将Item提交到数据库时,它肯定会给我错误:

This works well and keeps the code clean, but the critical issue is that when I want to commit the Item to the db, it surely will give me error :

 Incorrect integer value: '<class 'app.models.Item.State1'>' for column 'state' at row 1

那么,会话或python是否有一种方法可以在将类保存到数据库时自动将其转换为int表示形式,并在从数据库中检索到它时将其从int转换为其状态类?

So, is there a way for the session, or python, to automatically convert the class to its int representation when save into the db, and convert from the int to its state class when it is retrieved from the db?

推荐答案

您可以使用 TypeDecorator .像这样:

You can use a TypeDecorator. Something like:

class StateType(TypeDecorator):
    impl = Integer

    def process_bind_param(self, value, dialect):
        return map_integer_to_my_state(value)

    def process_result_value(self, value, dialect):
        return map_my_state_to_integer(value)

然后,您可以将StateType用作state列的类型:

Then you can use StateType as the type of the state column:

state = db.Column(StateType, ...)

这篇关于sqlalchemy如何使用自定义类作为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆