如何在sqlalchemy中使用自定义列类型时查找列名

2024-10-02 22:29:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在sqlalchemy中定义我自己的列类型:

class NonNegativeInt(TypeDecorator):
    impl = Integer

    def process_bind_param(self, value, dialect):
        if value is not None:
            if not isinstance(value, int) or value < 0:
                raise TypeError('Expect non-negative integer, find %s instead.' % value)
        return value

class Game(Model):
    score = Column(NonNegativeInt, default=0)

当我试图将一个负整数绑定到一个非负整数列(例如score)时,它会按预期引发一个错误:

^{pr2}$

但是,它没有指定列的名称,因此当列很多时不容易调试。当使用原始整数类型时,我得到了更具体的错误消息:

sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1366, u"Incorrect integer value: 'aaaa' for column 'score' at row 1")

如何找到有错误的列的名称(例如score)?此外,是否有可能在分配错误值时引发错误:game.score = -1,而不是在提交时?在


Tags: 名称类型if定义sqlalchemyvalue错误not