To Nha Notes | Jan. 27, 2021, 2:09 p.m.
Suppose that you are operating a web based product which implemented using Django framework and its data is increasing. To improve its performance as well as get efficiency in server cost, you want to pick up a few heaviest tables to migrate to new separated database server. And if you are scare to make too much changes in code, using Django's routers look like a good answer for you.
There is problem that need to sync tables which have references to others via foreign keys. So, how could we do that without changing so much in source code. Below is an alternative way:
Implement common base class for db models.
class MultiDbModel(models.Model):
class Meta:
abstract = True
def save(self, *args: Any, **kwargs: Any) -> None:
for dbname in settings.DATABASES:
super(MultiDbModel, self).save(using=dbname)
Inherits above class for db models which we want to write changes into multi-database.
class AdminUser(MultiDbModel):
email = models.EmailField(unique=True)
...