Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
Created June 28, 2011 00:34
Show Gist options
  • Save stephenmcd/1050211 to your computer and use it in GitHub Desktop.
Save stephenmcd/1050211 to your computer and use it in GitHub Desktop.
Safe concurrent saves for Django models
"""
With Django models, calling save() can have undesired consequences,
particularly in a concurrent environment such a Celery, where model
instances may be serialized across a message queue. The save() method
will write all fields to the database which may have already been
written to by another process or thread, and as such will override
fields incorrectly.
The mixin below can be used to safely update model instances without
overriding fields of no concern that may have been written to since
the object was instantiated.
Usage:
class SomeModel(UpdateMixin, models.Model):
# stuff
object.update(slug="myslug")
or
object.slug = "myslug"
object.update("slug")
"""
class UpdateMixin(object):
def update(self, *args, **kwargs):
for arg in args:
kwargs[arg] = getattr(self, arg)
self.__class__.objects.filter(id=self.id).update(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment