Skip to content

Instantly share code, notes, and snippets.

@sankalpjonn
Last active July 18, 2021 02:12
Show Gist options
  • Save sankalpjonn/d596adaf2f25e25e9fb3c37dc085b2f8 to your computer and use it in GitHub Desktop.
Save sankalpjonn/d596adaf2f25e25e9fb3c37dc085b2f8 to your computer and use it in GitHub Desktop.
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