﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
901	Reload method for models	andreas@…	Tim Graham	"'''reload''' is an additional model method that forces a models attributes to be reloaded from the database:

{{{
Index: django/core/meta/__init__.py
===================================================================
--- /home/andreas/workspace/django_src/django/core/meta/__init__.py	(revision 1396)
+++ /home/andreas/workspace/django_src/django/core/meta/__init__.py	(working copy)
@@ -528,7 +560,8 @@
         attrs['save'].alters_data = True
         attrs['delete'] = curry(method_delete, opts)
         attrs['delete'].alters_data = True
-
+        attrs['reload'] = curry(method_reload, opts)
+        
         if opts.order_with_respect_to:
             attrs['get_next_in_order'] = curry(method_get_next_in_order, opts, opts.order_with_respect_to)
             attrs['get_previous_in_order'] = curry(method_get_previous_in_order, opts, opts.order_with_respect_to)
@@ -775,6 +812,16 @@
 def method_eq(opts, self, other):
     return isinstance(other, self.__class__) and getattr(self, opts.pk.attname) == getattr(other, opts.pk.attname)
 
+def method_reload(opts, self):
+    pk_val = getattr(self, opts.pk.attname)
+    assert pk_val is not None, ""%s can't be loaded because it doesn't have an ID.""
+    kwargs = {'%s__exact' % opts.pk.attname : pk_val}
+    obj_list = function_get_list(opts, self._meta.get_model_module().Klass, **kwargs)
+    assert len(obj_list) == 1, \
+        ""Exactly one object should exist for %s %s -- %s objects exist!"" % \
+        (opts.pk.attname, pk_val, len(obj_list))
+    self.__dict__ = obj_list[0].__dict__
+
 def method_save(opts, self):
     # Run any pre-save hooks.
     if hasattr(self, '_pre_save'):
}}}

Here's a snippet useful e.g. for Ticket #555 (DateTimeFields with auto_now and auto_now_add don't change in place):

{{{
def _post_save(self):
    self.reload()
}}}
"	New feature	closed	Database layer (models, ORM)	dev	normal	fixed		simon@… kmike84@… aarongc@… james@… un33kvu@… mike@… mail@…	Ready for checkin	1	0	0	0	0	0
