Skip to content

Instantly share code, notes, and snippets.

@allieus
Created August 30, 2011 02:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allieus/1180032 to your computer and use it in GitHub Desktop.
Save allieus/1180032 to your computer and use it in GitHub Desktop.
Update for ONLY changed fields
from django.db import models
class ChangedOnlySaveModel(models.Model):
def __init__(self, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
self._initial_data = self.__dict__.copy()
def save(self, commit=True):
if not self.pk:
models.Model.save(self, commit)
else:
changed = []
for k, v in self._initial_data.iteritems():
if (v != self.__dict__[k]) and (k != '_initial_data'):
changed.append((k, v))
if len(changed) > 0:
self.__class__.objects.filter(pk=self.pk).update(**dict(changed))
self._initial_data = self.__dict__.copy()
class Meta:
abstract = True
from django.db import connection
class Post(ChangedOnlySaveModel):
title = models.Charfield(max_length=100)
content = models.TextField()
Post(title='title', content='content').save()
#
post = Post.objects.all()[0]
post.content = 'Hello World'
post.save()
print connection.queries
[{'time': '0.001', 'sql': u'UPDATE "phone_post" SET "content" = content WHERE "phone_post"."id" = 1 '}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment