What is the correct way to use refresh_from_db in Django?
Solution 1
This should be all you need to do to update one object. Replace object_name with your object.
object_name.refresh_from_db()
Solution 2
I assume the num_in_stock is an attribute of your model class. If true you should get an instance of the class (i.e object_name) then
object_name.refresh_from_db()
After which, you can access it like object_name.num_in_stock
Solution 3
I assume you're using an F expression
.
According to the documentation an F expression
:
...makes it possible to refer to model field values and perform database operations using them without actually having to pull them out of the database into Python memory.
You're working directly in the database. Python knows nothing about the values of the model fields. There's nothing on memory, everything is happening on the database.
The documentation's example:
from django.db.models import F
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()
Although
reporter.stories_filed = F('stories_filed') + 1
looks like a normal Python assignment of value to an instance attribute, in fact it’s an SQL construct describing an operation on the database.
So, for Python to know about this value you need to reload the object.
To access the new value saved this way, the object must be reloaded:
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()
In your example:
object_name.refresh_from_db()
And one more thing...
F() assignments persist after Model.save()
F() objects assigned to model fields persist after saving the model instance and will be applied on each save().
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()
reporter.name = 'Tintin Jr.'
reporter.save()
stories_filed
will be updated twice in this case. If it’s initially 1, the final value will be 3. This persistence can be avoided by reloading the model object after saving it, for example, by usingrefresh_from_db()
.
Related videos on Youtube
poleethman
Updated on June 13, 2022Comments
-
poleethman about 2 years
I'm using Django 1.8, Mezzanine, Cartridge, and I use Postgresql as the database.
I've updated the
num_in_stock
directly from the database. The quantities are all correct in the database but not on my website. I know the solution is here, but I don't know what to do with that. I really need it spelled out for me.How exactly would you use this in Cartridge to refresh the
num_in_stock
? -
KlausCPH about 2 yearsThis should be the accepted answer. The other answers do not explain why and when you need to use
refresh_from_db()