Skip to content

Instantly share code, notes, and snippets.

@jbwyme
Created December 19, 2013 00:24
Show Gist options
  • Save jbwyme/8032263 to your computer and use it in GitHub Desktop.
Save jbwyme/8032263 to your computer and use it in GitHub Desktop.
A little bit of poc code for optimistic locking within django
class ConcurrentUpdateException(Exception):
"""
Raised when a model can not be saved due to a concurrent update.
"""
class VersionedModel(models.Model):
_version = models.PositiveIntegerField(db_column='version', default=1)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
"""
Override the save method to delegate updates to a custom update method. Note that none of the
signals will be fired when updating.
"""
if self.id is None:
super(VersionedModel, self).save(force_insert=True, force_update=force_update, using=using, update_fields=update_fields)
else:
self._update_with_optimistic_locking()
def _update_with_optimistic_locking(self):
"""
This custom update method uses optimistic locking to handle concurrency issue. It will only execute the update
if no one has updated the row since we started making changes. This happens by making sure the version number
is the same when we write the updates as it was when we first read the row.
"""
kwargs = {}
for field in self._meta.fields:
kwargs[field.name] = getattr(self, field.name)
kwargs['_version'] += 1
affected = self.__class__.objects.filter(pk=self.id, _version=self._version).update(**kwargs)
if affected == 0:
raise ConcurrentUpdateException
class Meta:
abstract = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment