Skip to content

Instantly share code, notes, and snippets.

@groovecoder
Created August 9, 2012 16:34
Show Gist options
  • Save groovecoder/3305665 to your computer and use it in GitHub Desktop.
Save groovecoder/3305665 to your computer and use it in GitHub Desktop.
def update(self, **kw):
"""
Shortcut for doing an UPDATE on this object.
If _signal=False is in ``kw`` the post_save signal won't be sent.
"""
signal = kw.pop('_signal', True)
cls = self.__class__
using = kw.pop('using', 'default')
for k, v in kw.items():
setattr(self, k, v)
if signal:
# Detect any attribute changes during pre_save and add those to the
# update kwargs.
attrs = dict(self.__dict__)
models.signals.pre_save.send(sender=cls, instance=self)
for k, v in self.__dict__.items():
if attrs[k] != v:
kw[k] = v
setattr(self, k, v)
cls.objects.using(using).filter(pk=self.pk).update(**kw)
if signal:
models.signals.post_save.send(sender=cls, instance=self,
created=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment