Skip to content

Instantly share code, notes, and snippets.

@vsego
Created August 9, 2018 13:41
Show Gist options
  • Save vsego/79685a98efd2b3276330d1f96a123a0b to your computer and use it in GitHub Desktop.
Save vsego/79685a98efd2b3276330d1f96a123a0b to your computer and use it in GitHub Desktop.
A context manager for easily locking model instances
@contextmanager
def lock_model(model_class, **kwargs):
with transaction.atomic():
yield model_class.objects.select_for_update().get(**kwargs)
# Usage
with lock_model(ModelClass, pk=some_pk) as instance:
do something with instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment