Skip to content

Instantly share code, notes, and snippets.

View uday12kumar's full-sized avatar

Uday Kumar uday12kumar

  • Netplay sports pvt ltd
  • Hyderabad
View GitHub Profile
@uday12kumar
uday12kumar / slot_model.py
Last active January 28, 2020 12:52
Django concurrency
class Slot(models.Model): 
id = models.AutoField(primary_key=True,)
user = models.ForeignKey(User)  
seats= models.IntegerField(default=10)
def book(self, seats_selected,slot_id):
if self.seats < self.seats_selected:
raise errors.InsufficientSeats() 
self.seats -= seats_selected
self.save()
def cancel_booking(self, seats_selected):
  self.seats += seats_selected
  self.save()
@classmethod
def cancel(cls, id, seats_selected):
with transaction.atomic():
slot= (cls.objects.select_for_update().get(id=id))
slot.seats += seats_selected
slot.save()
return slot
@classmethod
def book(cls, id, seats_selected):
with transaction.atomic():
if seats < self.seats_selected:
raise errors.InsufficientSeats()
slot = (cls.objects.select_for_update().get(id=id))
slot.seats -= seats_selected
slot.save()
return slot