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.?

  • 1
    Possible duplicate of [Django Multiple Databases Fallback to Master if Slave is down](https://stackoverflow.com/questions/26608906/django-multiple-databases-fallback-to-master-if-slave-is-down) – kmcodes Nov 20 '17 at 06:42
  • Please check [this solution](https://stackoverflow.com/questions/26608906/django-multiple-databases-fallback-to-master-if-slave-is-down). Its a more detailed version of your question. – kmcodes Nov 20 '17 at 06:43

1 Answers1

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

Hayden
  • 449
  • 4
  • 13
  • 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. – albinantony143 Nov 20 '17 at 10:01
  • separation of write and read can be implemented by django db router. I think Switch of Master and Slave can be done by DevOps. – Hayden Nov 21 '17 at 01:45