Reload django object from database


Is it possible to refresh the state of a django object from database? I mean behavior roughly equivalent to:

new_self = self.__class__.objects.get(
for each field of the record:
    setattr(self, field, getattr(new_self, field))

UPDATE: Found a reopen/wontfix war in the tracker:
Still don’t understand why the maintainers don’t like this.

Asked By: grep



I’ve found it relatively easy to reload the object from the database like so:

x = X.objects.get(
Answered By: Amandasaurus

In reference to @grep’s comment, shouldn’t it be possible to do:

# Put this on your base model (or monkey patch it onto django's Model if that's your thing)
def reload(self):
    new_self = self.__class__.objects.get(
    # You may want to clear out the old dict first or perform a selective merge

# Use it like this = foo
assert is None
assert is foo and is not None
Answered By: Eloff

As of Django 1.8 refreshing objects is built in. Link to docs.

def test_update_result(self):
    obj = MyModel.objects.create(val=1)
    MyModel.objects.filter('val') + 1)
    # At this point obj.val is still 1, but the value in the database
    # was updated to 2. The object's updated value needs to be reloaded
    # from the database.
    self.assertEqual(obj.val, 2)
Answered By: Tim Fletcher

As @Flimm pointed out, this is a really awesome solution:


This reloads all data from the database into the object.

Answered By: Ron
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.