Refresh a Django object from the database

Problem - Updating objects with a view that you've already got a reference to

While writing unittests for a django application, I would create an instance of a model in the setUp(), then call some view in the test, using the django test client. I would then like to test the original object from the setUp.

This is easy enough, however I ran into a problem where it looked like the object wasn't being updated by my view function. It turns out it was because Django had loaded that object from the database at the start, and hadn't updated it after my view function.

Solution - Reload the object from the database

The solution is to reload the object from the database (to 'refresh' it). You can do it with this command:

x = X.objects.get(id=x.id)

Replace X with the name of your model class, and x with the variable you had assigned the object to

x should now be the most up to date version of that object and should have any attributes set

There is a long standing django feature request to add this reload method, however the django developers have decided that this work around is easy enough.

This entry is tagged: