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.).

A 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 Record and 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.

Written by

Full Stack Developer, Team Leader, Independent. More from me at https://hakibenita.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store