Django model reload_from_db() vs. explicitly recalling from db
<p>If I have an object retrieved from a model, for example:</p>

<pre><code>obj = Foo.objects.first()
</code></pre>

<p>I know that if I want to reference this object later and make sure that it has the current values from the database, I can call:</p>

<pre><code>obj.refresh_from_db()
</code></pre>

<p>My question is, is there any advantage to using the <code>refresh_from_db()</code> method over simply doing?:</p>

<pre><code>obj = Foo.objects.get(id=obj.id)
</code></pre>

<p>As far as I know, the result will be the same. <code>refresh_from_db()</code> seems more explicit, but in some cases it means an extra line of code. Lets say I update the <code>value</code> field for <code>obj</code> and later want to test that it has been updated to <code>False</code>. Compare:</p>

<pre><code>obj = Foo.objects.first()
assert obj.value is True
# value of foo obj is updated somewhere to False and I want to test below
obj.refresh_from_db()
assert obj.value is False
</code></pre>

<p>with this:</p>

<pre><code>obj = Foo.objects.first()
assert obj.value is True
# value of foo obj is updated somewhere to False and I want to test below
assert Foo.objects.get(id=obj.id).value is False
</code></pre>

<p>I am not interested in a discussion of which of the two is more pythonic. Rather, <strong>I am wondering if one method has a practical advantage over the other in terms of resources, performance, etc</strong>. I have read <a href="https://docs.djangoproject.com/en/1.10/ref/models/instances/#refreshing-objects-from-database" rel="nofollow">this bit of documentation</a>, but I was not able to ascertain from that whether there is an advantage to using <code>reload_db()</code>. Thank you!</p>

<p>Django sources are usually relatively easy to follow. If we look at the <a href="https://github.com/django/django/blob/master/django/db/models/base.py#L656" rel="nofollow">refresh_from_db() implementation</a>, at its core it is still using this same  <code>Foo.objects.get(id=obj.id)</code> approach:</p>

<pre><code>db_instance_qs = self.__class__._default_manager.using(db).filter(pk=self.pk)
...
db_instance_qs = db_instance_qs.only(*fields)
...
db_instance = db_instance_qs.get()
</code></pre>

<p>Only there are couple extra bells and whistles:</p>

<ul>
<li><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.defer" rel="nofollow">deferred</a> fields are ignored</li>
<li>stale foreign key references are cleared (according to the comment explanation)</li>
</ul>

<p>So for everyday usage it is safe to say that they are pretty much the same, use whatever you like.</p>

python django django-models