Django Db routing

Depending on the size of the data and the application I'd tackle this with either of the following methods:

  1. Database pinning:

Extend your database router to allow pinning functions to specific databases. For example:

from customrouter.pinning import use_master

@use_master
def save_and_fetch_foo():
    ...

A good example of that can be seen in django-multidb-router. Of course you could just use this package as well.

  1. Use a model manager to route queries to specific databases.

    class MyManager(models.Manager):
        def get_queryset(self):
            qs = CustomQuerySet(self.model)
            if self._db is not None:
                qs = qs.using(self._db)
            return qs
    
  2. Write a middleware that'd route your requests to master/slave automatically. Basically same as the pinning method but you wouldn't specify when to run GET requests against master.

Tags:

Python

Django