Created
August 30, 2011 02:37
-
-
Save allieus/1180032 to your computer and use it in GitHub Desktop.
Update for ONLY changed fields
This file contains 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
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 |
This file contains 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
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 |
This file contains 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
[{'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