Creating routers for multiple databases in Django

Asked

Viewed 79 times

3

I am developing a Django application where I need several Databases, one for each user of the system. For this I set the Databases like this:


DATABASES = {
    'default': {},
    'primary': {
        'NAME': 'primary',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'spam',
    },
    'user1': {
        'NAME': 'user1',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'eggs',
    },
    'user2': {
        'NAME': 'user2',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'PASSWORD': 'bacon',
    },
}

In which the bank user1 and user2 are replicas of the structure of primary.

Let’s say I created two superusers, with the logins 'superuser1' and 'superuser2'. How do I set that when superuser1 is logged in the data is changed in user1 database and when superuser2 is logged in the data in user2 database'?

2 answers

2

1

A native alternative would be to use the database routing, see the example that documentation provides, when using database routing Django offers an API for specify on which basis you want to save using the following code

>>> p = Person(name='Fred')
>>> p.save(using='first')  # usa o banco de dados "first"
>>> p.save(using='second') # usa o banco de dados "second"

you can also delete choosing a specific database

>>> u = User.objects.using('legacy_users').get(username='fred')
>>> u.delete() # will delete from the `legacy_users` database

Browser other questions tagged

You are not signed in. Login or sign up in order to post.