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, ...)