Hey Sina, that’s a great question.
In the article Balance is the name of the model, and the name of a calculated field. In the real world, as in my actual implementation, there is a record of actions made to the balance (such as deposit, withdraw, charge, refund etc.).
Record model would usually have a Foreign key to the Balance model, and the instances will be immutable (e.g records are only ever created, never updated or deleted).
Any action on the balance will be implemented as a
@classmethod on the Balance model, and will do the following:
- Fetch the balance instance and obtain a lock on the database row (to prevent concurrent modifications).
- Perform any check of validation (i.e sufficient funds).
- Create a new
Recordand add it to the records table, with a foreign key to the balance.
- commit and release the lock.
TLDR; Any action on the balance always go through a top-level model which has the ability to prevent concurrent modifications.