Getting old attribute value into entity hooks before_update() in ponyORM

119 Views Asked by At

I have the following db classes:

class Account(db.Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    balance = Required(Decimal, precision=2, default=0)
    transactions = Set('Transaction')


class Transaction(db.Entity):
    id = PrimaryKey(int, auto=True)
    datetime = Required(datetime, precision=0, default=lambda: datetime.now())
    account = Required(Account)
    value = Required(Decimal, precision=2)
    description = Optional(str)

    def after_insert(self):
        self.account.balance += self.value

    def before_delete(self):
        self.account.balance -= self.value

    def before_update(self):
        pass

I did not find a way to reduce the balance like:

def before_update(self):
    self.account.balance += self.value - self.value.old_value

Is there any way to get the old attribute value?

1

There are 1 best solutions below

0
Arol On

I found a loophole:

class Account(db.Entity):
    id = PrimaryKey(int, auto=True)
    name = Required(str)
    balance = Required(Decimal, precision=2, default=0)
    transactions = Set('Transaction')


class Transaction(db.Entity):
    id = PrimaryKey(int, auto=True)
    datetime = Required(datetime, precision=0, default=lambda: datetime.now())
    account = Required(Account)
    value = Required(Decimal, precision=2)
    description = Optional(str)

    def after_insert(self):
        self.account.balance += self.value

    def before_delete(self):
        self.account.balance -= self.value

    def before_update(self):
        self._old_value = self._dbvals_[Transaction.value]

    def after_update(self):
        self.account.balance += self.value - self._old_value