K
K
k0r0g2021-05-02 22:17:25
Django
k0r0g, 2021-05-02 22:17:25

How do database routers work?

Hello. I have 2 tables. I want to spread them to different bases. One in the default, the other - in the new.
settings file:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'registrations': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': '../db.sqlite3'
    }
}
DATABASE_ROUTERS = ['nails.router.RegRouter']

The router file is in the same folder as settings:
class RegRouter:
    def db_for_read(self, model, **hints):
        if model._meta.db_table == 'registrations':
            return 'registrations'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.db_table == 'registrations':
            return 'registrations'
        return None

My models:
class Service(models.Model):
    title = models.CharField('Название услуги', max_length=100, name="title")
    cost = models.DecimalField('Стоимость', name="cost", max_digits=6, decimal_places=2)
    duration = models.IntegerField('Длительность в минутах', name="duration")
    image = models.ImageField('Изображение карточки', upload_to="main/static/main/img")

    def __str__(self):
        return self.title


class Registration(models.Model):
    title = models.CharField('Тест', max_length=100, name="title", default='')

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'registrations_table'

Why are all tables written to both databases when I perform a migration?
(obviously I run the second migration as python manage.py migrate --database=registrations)
How can I avoid this? What did I do wrong in the router?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
k0r0g, 2021-05-02
@k0r0g

I'm a complete fool. Didn't make a migration resolution algorithm.
It somehow turned out like this. Correct it if you can

spoiler
class RegRouter:
    def db_for_read(self, model, **hints):
        if model._meta.db_table == 'registrations_table':
            return 'registrations'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.db_table == 'registrations_table':
            return 'registrations'
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if db == 'registrations' and model_name == 'registration':
            return True
        if db == 'registrations' and model_name != 'registration':
            return False
        if db == 'default' and model_name == 'registration':
            return False
        else:
            return True

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question