Last active
July 18, 2021 02:12
-
-
Save sankalpjonn/d596adaf2f25e25e9fb3c37dc085b2f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.contrib.auth.models import User | |
from django.db import models, transaction | |
class Account(models.Model): | |
balance = models.IntegerField(default=0) | |
user = models.ForeignKey(User) | |
def get_queryset(self): | |
return self.__class__.objects.filter(id=self.id) | |
@transaction.atomic() | |
def deposit(self, amount): | |
obj = self.get_queryset().select_for_update().get() | |
obj.balance += amount | |
obj.save() | |
@transaction.atomic() | |
def withdraw(self, amount): | |
obj = self.get_queryset().select_for_update().get() | |
if amount > obj.balance: | |
raise errors.InsufficientFunds() | |
obj.balance -= amount | |
obj.save() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment