Django: Multiple database for read and write independent of app

2k views Asked by At

How can we work with multiple databases on Django, under some specific conditions such as,

1. One DB for write purpose only ( db_for_write.sqlite3)
2. Two other DB for reading purposes (read_replica_1.sqlite3 ,read_replica_2.sqlite3)
3. All these 3 DB should be synchronized all the time (3 DB should contain same data all the time)
4. All the actions such as CRUD , migration etc are independent of app or model

this is my Db_Router.py

import random


class ExampleDatabaseRouter(object):
    def db_for_read(self, model, **hints):
        db_list = ('db_for_read_1', 'db_for_read_2')
        return random.choice(db_list)

    def db_for_write(self, model, **hints):
        return 'db_for_write_only'

    def allow_relation(self, obj1, obj2, **hints):
        # I couldn't understand what would do this method
        return

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        # sync all DB
        return


Unfortunately, I couldn't understand the purpose of allow_relation() method. I hope someone could help me.

1

There are 1 answers

1
zaidfazil On

From the documentation,

allow_relation(obj1, obj2, **hints)¶

Return True if a relation between obj1 and obj2 should be allowed, False if the relation should be prevented, or None if the router has no opinion. This is purely a validation operation, used by foreign key and many to many operations to determine if a relation should be allowed between two objects.

As in the documentation, this method only determines if the objects passed into it are eligible to create a relation between them. When using multiple databases, there may arise a situation where tables from separate databases require a relationship between them, but Django currently doesn't support these kind of relationships, which are often referred as cross-database relationships. This is because of referential integrity. In order to maintain a relationship between two objects, Django needs to know that the primary key of the related object is valid. If the primary key is stored on a separate database, it’s not possible to easily evaluate the validity of a primary key.

If you need to look more into cross-database relationships, then django documentation provides a much better explanation.

Actually, Django documentation covers pretty much everything about routers. A pretty basic example have also included here.