[Django]-Django specify which database to use for module

4👍

You can read on django database routers for this, some good examples can be found online as well and they should be straightforward.

Another solution would be to modify the Model manager.

from django.db import models


class ReplicaRoutingManager(models.Manager):
    def get_queryset(self):
        queryset = super().get_queryset(self)

        if settings.ENV == 'production':
            return queryset.using('read-replica')

        return queryset


class Customer(models.Model):

    ...
    objects = models.Manager()
    replica_objects = ReplicaRoutingManager()

with this, you can just use the normal Customer.objects.filter and the manager should do the routing.

I still suggest going with the database router solution, and creating a custom logic in the class. But if the manager works for you, its fine.

1👍

If you want All the queries in the email_lists app to query read-replica, then a router is the way to go. If you need to query different databases within the same app, then @ibaguio’s solution is the way to go. Here’s a basic router example similar to what I’m using:

project/database_routers.py

MAP = {'some_app': 'default',
       'some_other_app': 'default',
       'email_lists': 'read-replica',}

class DatabaseRouter:

    def db_for_read(self, model, **hints):
        return MAP.get(model._meta.app_label, None)

    def db_for_write(self, model, **hints):
        return MAP.get(model._meta.app_label, None)

    def allow_relation(self, object_1, object_2, **hints):
        database_object_1 = MAP.get(object_1._meta.app_label)
        database_object_2 = MAP.get(object_2._meta.app_label)
        return database_object_1 == database_object_2

    def allow_migrate(self, db, app_label, model=None, **hints):
        return MAP.get(app_label, None)

In settings.py:

DATABASE_ROUTERS = ['project.database_router.DatabaseRouter',]

It looks like you only want it in production, so I would think you could add it conditionally:

if ENV == 'production':
    DATABASE_ROUTERS = ['project.database_router.DatabaseRouter',]

Leave a comment