python - Sqlalchemy:在另一列发生更改时自动计算一列的值

标签 python sqlalchemy

我希望使用某种方法计算列的值 (is_dangerous_token)。 这是我到目前为止所做的。

class PassRecovery(DeclarativeBase):
    __tablename__ = 'pass_recoveries'

    id = Column(Integer, primary_key=True)
    account_email_address = Column(Unicode(255), ForeignKey('accounts.email_address'), index=True)
    account = relationship('Account', backref=backref('pass_recoveries', cascade='all, delete-orphan'))
    _is_dangerous_token = Column('is_dangerous_token', Unicode(255))

    def _set_is_dangerous_token(self, account_email_address):
        secret_key = config.get('is_dangerous_key')
        signer = TimestampSigner(secret_key)
        self._is_dangerous_token = signer.sign(account_email_address)

    def _get_is_dangerous_token(self):
        return self._is_dangerous_token

    is_dangerous_token = synonym(
        '_is_dangerous_token',
        descriptor=property(_get_is_dangerous_token, _set_is_dangerous_token)
    )

但问题是,当我通过传入 email_address 创建一行时,is_dangerous_token 不是使用我编写的代码生成的。创建的行仅具有id以及与account的关系,并且is_dangerous_token在数据库中没有值。 感谢您的帮助

最佳答案

您必须在 account_email_address 列上使用 synonym,因为您需要它的值来生成 token :

class PassRecovery(DeclarativeBase):
    __tablename__ = 'pass_recoveries'

    id = Column(Integer, primary_key=True)
    _account_email_address = Column(Unicode(255), ForeignKey('accounts.email_address'), index=True)
    account = relationship('Account', backref=backref('pass_recoveries', cascade='all, delete-orphan'))
    is_dangerous_token = Column('is_dangerous_token', Unicode(255))

    def _set_account_email_address(self, account_email_address):
        self._account_email_address = account_email_address

        secret_key = config.get('is_dangerous_key')
        signer = TimestampSigner(secret_key)
        self.is_dangerous_token = signer.sign(self._account_email_address)

    def _get_account_email_address(self):
        return self.account_email_address

    account_email_address = synonym(
        '_account_email_address',
        descriptor=property(_get_account_email_address, _set_account_email_address)
    )

编辑 1

假设 Persoan.A 是同义词。

session.query(Person).filter(Person.A > 8)

因此,您可以在查询中使用数据库中不存在的列来计算复杂的表达式。

但是你不能用属性来做到这一点,在你的情况下,最好简单地使用 python 的属性而不是同义词,以避免 sqlalchemy 同义词的成本。

另一种方法是使用 sqlalchemy events ,监听属性的更改,并在引发事件时执行您想要的操作。

关于python - Sqlalchemy:在另一列发生更改时自动计算一列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40356067/

相关文章:

python - PySpark 广播变量连接

python - 路径 "."和 "./"以及 "./."之间的差异

python - 如何使用 tkinter 打开 .gif 文件而不出现错误 "Too early to create image"?

python - Flask-SQLAlchemy 查询计数

python - SQLAlchemy:查询包含数组和计数匹配项的 JSON 列 (PostgreSQL)

javascript - Python 列表未在 javascript 中呈现

python - 列表在Python3.6

python - 使用 session.query 读取 SQLAlchemy 中未提交的数据

python - SQLAlchemy session 重新连接

python - OperationalError "unable to open database file"使用 SQLAlchemy 和 SQLite3 处理查询结果