After reading django multiple database documentation we can use multiple database but can’t keep clone object in our database. Let explain little bit assume you have two model teacher and student. You can use two separate database for teacher and student but you can’t use another database for keep clone objects of your teacher and student model. So here we will use django siganls for keep clone objects in our replica_database. Signals will be triggered and create clone object whenever any objects create in our model. Here is my code:
settings.py
'default': {
'NAME': 'primary_database',
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'USER': 'root',
'PASSWORD': '',
},
'replica1_database': {
'NAME': 'replica1_database',
'ENGINE': 'django.db.backends.mysql',
'HOST': 'localhost',
'USER': 'root',
'PASSWORD': '', },
models.py:
from django.db.models.signals import post_save
from django.dispatch import receiver
class Contact(models.Model):
name = models.CharField(blank=True, null=True, max_length=100)
@receiver(post_save, sender=Contact, dispatch_uid="clone_objects")
def replica1_databse(sender, instance, created, **kwargs):
if created: #cerate clone object
obj = instance
obj.save(using='replica1')
else: #updating clone object
obj = Contact.objects.using('replica1').update(
name=instance.name)
Here I am triggering signals for create an clone objects in my replica1_database.
Now run python manage.py makemigrtions contact
and python manage.py migrate contact
this two migrations applied in your default database. This is the most important step ----> You have to run python manage.py migrate --database=replica1
This migrate applied for your replica1 database .
I Think it also an good idea to keep an backup database for avoid any unexcepted situation such as server down.