I
I
IvanOne2015-11-11 09:43:49
Django
IvanOne, 2015-11-11 09:43:49

Competitive requests in django?

Hello! Suggest a solution. There is a Profile model with a balance field, which is stored in the database in decimal.
The Profile model has a method that changes the balance:

def update_profile(self, amount):
      self.balance += amount
      if self.balance < 0:
          return False
      else:
          self.save(update_fields=["balance"])
          return True

As far as I understand, if there is a competitive request, then the value will be written incorrectly. I read about select_for_update, but as far as I understand it can only be used with transactions. Tried to test this method in TestCase and TransactionTestCase got error:
TransactionManagementError: select_for_update cannot be used outside of a transaction.
I also saw a solution through the F object, but everything happens immediately in the update method, but I need to check for a negative value. What can you advise?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question