如何在 sqlalchemy 中将默认值设置为自定义类型?
How to set default value to a custom type in sqlalchemy?
我想为我的自定义列类型设置列默认值。
目前我有这个:
score = Column(ScoreType, default=Score())
或
score = Column(ScoreType, ColumnDefault(Score()))
我创建了一个数据库条目,但没有使用 score=Score()
显式设置分数。当我尝试访问 score
实例 (entry.score.total += 1
) 时,出现错误 AttributeError: 'NoneType' object has no attribute 'total'
。
如果我创建一个带有显式分数设置的数据库条目,那么它就可以工作。
例如,以下 DateTime
类型有效:
timestamp = Column(DateTime, ColumnDefault(datetime.datetime.now()))
我的类型 class 看起来像这样:
class ScoreType(types.TypeDecorator):
impl = types.String
def process_bind_param(self, value, dialect):
return repr(value)
def process_result_value(self, value, dialect):
return Score.create_score(value)
我为此使用另一个 class:
class Score:
def __init__(self, result: int = 0, total: int = 0):
self.total = total
self.result = result
def __repr__(self):
return f"{self.result}/{self.total}"
@classmethod
def create_score(cls, string: str) -> 'Score':
r, t = int(string.split('/'))
return cls(result=int(r), total=int(t))
知道如何设置默认值吗?
Another question on Whosebug 处理了类似的主题。但是,它并不完全符合我的问题,还没有得到最终的答复。
我已经通过调整init方法解决了问题:
if not kwargs.get('score'):
self.score = Score()
我想为我的自定义列类型设置列默认值。
目前我有这个:
score = Column(ScoreType, default=Score())
或
score = Column(ScoreType, ColumnDefault(Score()))
我创建了一个数据库条目,但没有使用 score=Score()
显式设置分数。当我尝试访问 score
实例 (entry.score.total += 1
) 时,出现错误 AttributeError: 'NoneType' object has no attribute 'total'
。
如果我创建一个带有显式分数设置的数据库条目,那么它就可以工作。
例如,以下 DateTime
类型有效:
timestamp = Column(DateTime, ColumnDefault(datetime.datetime.now()))
我的类型 class 看起来像这样:
class ScoreType(types.TypeDecorator):
impl = types.String
def process_bind_param(self, value, dialect):
return repr(value)
def process_result_value(self, value, dialect):
return Score.create_score(value)
我为此使用另一个 class:
class Score:
def __init__(self, result: int = 0, total: int = 0):
self.total = total
self.result = result
def __repr__(self):
return f"{self.result}/{self.total}"
@classmethod
def create_score(cls, string: str) -> 'Score':
r, t = int(string.split('/'))
return cls(result=int(r), total=int(t))
知道如何设置默认值吗?
Another question on Whosebug 处理了类似的主题。但是,它并不完全符合我的问题,还没有得到最终的答复。
我已经通过调整init方法解决了问题:
if not kwargs.get('score'):
self.score = Score()