Django Db routing
<p>I am trying to run my Django application with two db's (1 master, 1 read replica). My problem is if I try to read right after a write the code explodes. For example:</p>

<ul>
<li>p = Product.objects.create()</li>
<li><ol>
<li>Product.objects.get(id=p.id)</li>
</ol></li>
</ul>

<p>OR</p>

<ul>
<li><ol start="2">
<li>If user is redirected to Product's
details page</li>
</ol></li>
</ul>

<p>The code runs way faster than the read replica. And if the read operation uses the replica the code crashes, because it didn't update in time. </p>

<p>Is there any way to avoid this? For example, the db to read being chosen by request instead of by operation?</p>

<p>My Router is identical to Django's documentation:</p>

<pre><code>import random

class PrimaryReplicaRouter(object):
    def db_for_read(self, model, **hints):
        """
        Reads go to a randomly-chosen replica.
        """
        return random.choice(['replica1', 'replica2'])

    def db_for_write(self, model, **hints):
        """
        Writes always go to primary.
        """
        return 'primary'

    def allow_relation(self, obj1, obj2, **hints):
        """
        Relations between objects are allowed if both objects are
        in the primary/replica pool.
        """
        db_list = ('primary', 'replica1', 'replica2')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        """
        All non-auth models end up in this pool.
        """
        return True
</code></pre>

<p>IN master replica conf the new data will take few millisecond to replicate the data on all other replica server/database.</p>

<p>so whenever u tried to read after write it wont gives you correct result.</p>

<p>Instead of reading from replica you can use master to read immediately after  write by using <code>using('primary')</code> keyword with your get query.</p>

python django