0

I want to write to add, update delete to multiple database by using django.db.models.Model

I am able to add to multiple database by setting up multi-db in settings.py

So setting file look like

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config['DB_NAME'],
        'USER': config['DB_USER'],
        'PASSWORD': config['DB_PASSWORD'],
        'HOST': config['DB_HOST'],
        'PORT': config['DB_PORT'],
    },
    'tableau': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'tableau',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'localhost',
        'PORT': 5432,
    },
}

Then I create subclass of django.db.models.Model and model in my app's model.py

from django.db.models import Model

class MultiDbModel(Model):
    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        for dbname in settings.DATABASES:
            super(MultiDbModel, self).save(using=dbname)

class People(MultiDbModel):
    name = CharField(max_length=255)
    country = CharField(max_length=255)

        def save(self, *args, **kwargs):
            super(App, self).save(args, kwargs)

So when I am creating new object its getting saved to both database.

People.objects.create(name='alok', location='India')

To this approach I want to add capability of update and delete query also like create is working properly.

What methods get called when update and delete query runs or how can I add capability of delete and update to multiple database?

Community
  • 1
  • 1
Alok
  • 7,734
  • 8
  • 55
  • 100

1 Answers1

0

I would override admin methods.save_model caters both create and update method. add delete_model for deleting object.

Refer to: https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#modeladmin-methods

webbyfox
  • 1,049
  • 10
  • 22