Skip to content

Instantly share code, notes, and snippets.

@dcramer
Created August 25, 2010 22:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcramer/550436 to your computer and use it in GitHub Desktop.
Save dcramer/550436 to your computer and use it in GitHub Desktop.
diff --git a/django_root/django/db/models/base.py b/django_root/django/db/models/base.py
index 37331b3..4da2802 100644
--- a/django_root/django/db/models/base.py
+++ b/django_root/django/db/models/base.py
@@ -5,6 +5,7 @@ from itertools import izip
import django.db.models.manager # Imported to register signal handler.
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, FieldError, ValidationError, NON_FIELD_ERRORS
from django.core import validators
+from django.db.models.expressions import ExpressionNode
from django.db.models.fields import AutoField, FieldDoesNotExist
from django.db.models.fields.related import OneToOneRel, ManyToOneRel, OneToOneField
from django.db.models.query import delete_objects, Q
@@ -436,6 +437,20 @@ class Model(object):
save.alters_data = True
+ def update(self, using=None, **kwargs):
+ """
+ Updates specified attributes on the current instance.
+ """
+ assert self.pk, "Cannot update an instance that has not yet been created."
+ self.__class__._base_manager.using(using).filter(pk=self.pk).update(**kwargs)
+ for k, v in kwargs.iteritems():
+ if isinstance(v, ExpressionNode):
+ # NotImplemented
+ continue
+ setattr(self, k, v)
+
+ update.alters_data = True
+
def save_base(self, raw=False, cls=None, origin=None, force_insert=False,
force_update=False, using=None):
"""
diff --git a/django_root/tests/modeltests/update/tests.py b/django_root/tests/modeltests/update/tests.py
index 05397f8..ea7259e 100644
--- a/django_root/tests/modeltests/update/tests.py
+++ b/django_root/tests/modeltests/update/tests.py
@@ -1,4 +1,5 @@
from django.test import TestCase
+from django.db.models import F
from models import A, B, D
@@ -47,3 +48,17 @@ class SimpleTest(TestCase):
self.failUnlessEqual(num_updated, 0)
cnt = D.objects.filter(y=100).count()
self.failUnlessEqual(cnt, 0)
+
+ def test_self_update(self):
+ """
+ Test the update method attached to an instance.
+ """
+ self.a1.update(x=100)
+ self.failUnlessEqual(self.a1.x, 100)
+
+ def test_self_update_with_expressions(self):
+ """
+ Test the update method with expressions which are not implemented.
+ """
+ self.a1.update(x=F('x') + 100)
+ self.failUnlessEqual(self.a1.x, 10)
\ No newline at end of file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment