Redirect database call to different db url based on type of query(Read, write, update) with Django

68 views Asked by At

In an existing project, how can I implement a method using which I can redirect it different database(Write, Update & read) without modifying existing Django queries?

If I have 2 queries:

  1. MyModel.objects.get(name = "abc") And
  2. MyModel.objects.create(name = "xyz")

With database config as:

DATABASES = {
       'read_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'read_db',
        'USER': 'read_db',
        'PASSWORD': 'read_db',
        'HOST': '',
        'PORT': '',
    },
    'write_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'write_db',
        'USER': 'write_db',
        'PASSWORD': 'write_db',
        'HOST': '',
        'PORT': '',
    },
    'update_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'update_db',
        'USER': 'update_db',
        'PASSWORD': 'update_db',
        'HOST': '',
        'PORT': '',
    }
}

Want read_db to be called for query 1 & write_db for query 2

1

There are 1 answers

0
Mega On

Take a look at Django's Database Routers. You can specify your db_for_read and db_for_write without having to change the queries.