3

From django documentation, is possible create replica from database and define where it will write or read. (django multiple-database).

Then, it wrote the code for it, configuring my DATABASE like:

DATABASES = {
    'default': {
        'NAME': 'my_write_database',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'writedatabase',
    },
    'replica': {
        'NAME': 'replica',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'readdatabase',
    },
}

And create the router:

class ReplicaDatabaseWriteRead(object):

    route_app_labels = {..all_possible_applications}

    def db_for_read(self, model, **hints):
        return 'replica' # O just wanna read from 'replica'

    def db_for_write(self, model, **hints):
        if model._meta.app_label in self.route_app_labels:
            return 'default' # I wanna write in default and 'reflect' to 'replica'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        db_list = (..all_possible_apps)
        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):
        return True

But this not works correctly. When I is writing, it just write in default, does not reflecting to replica. Then when I read the replica, the values does not exits.

Shouldn't he have written in the default and replicated the value in the replica? I'm using django-rest-framework This code is very similarity of documentation, I don't know what's wrong. Or I don't understand the django documentation?

markwalker_
  • 12,078
  • 7
  • 62
  • 99
willteam
  • 117
  • 7

1 Answers1

7

Django does not solve the problem of replication for you.

Usual approach for replication - one database for write with several replicas for read. Replication is done on database level (not django), i.e. database is configured to write its transaction log, read-replicas sync this log and replay it.

Django multiple database configuration allows to specify different database URLs for read and write, and / or specify different databases for different applications or even tables - which is more a concern of database clustering, not replication.

Oleg Russkin
  • 4,234
  • 1
  • 8
  • 20