Created
August 9, 2018 13:41
-
-
Save vsego/79685a98efd2b3276330d1f96a123a0b to your computer and use it in GitHub Desktop.
A context manager for easily locking model instances
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
@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