0

I have set up a Master remote MySQL database server and a replica of it configured as a slave database for my Django application. Both running on amazon ubuntu ec2 instance. How can I configure Django to access slave database automatically in case the Master database is down.?

2

1 Answer 1

1

Djangor use db router to resolve this question, I give you a example:

class DBRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
    """
    Attempts to read auth models go to auth_db.
    """
    if model._meta.app_label == 'xxx':
        return 'salvedb' # this name you defined in settings of django project
    return None

def db_for_write(self, model, **hints):
    """
    Attempts to write auth models go to auth_db.
    """
    if model._meta.app_label == 'xxx':
        return 'salvedb'
    return None

def allow_relation(self, obj1, obj2, **hints):
    """
    Allow relations if a model in the auth app is involved.
    """
    #if obj1._meta.app_label == 'auth' or \
    #   obj2._meta.app_label == 'auth':
    #   return True
    return None

def allow_migrate(self, db, app_label, model_name=None, **hints):
    """
    Make sure the auth app only appears in the 'auth_db'
    database.
    """
    #if app_label == 'auth':
    #    return db == 'auth_db'
    return None

and add this router to your settings:

DATABASE_ROUTERS = ['path.routers.DBRouter']

or you can read the docs on django official site:https://docs.djangoproject.com/en/1.11/topics/db/multi-db/#automatic-database-routing

Sign up to request clarification or add additional context in comments.

2 Comments

I guess your solution is for storing different model data in separate DB.I am not using separate DB for different apps. I am storing all apps data in master DB and slave DB in sync with it. All I want is to make sure that if the master fails, Django should read and write from slave DB.
separation of write and read can be implemented by django db router. I think Switch of Master and Slave can be done by DevOps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.