Answer the question
In order to leave comments, you need to log in
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']
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
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'
Answer the question
In order to leave comments, you need to log in
I'm a complete fool. Didn't make a migration resolution algorithm.
It somehow turned out like this. Correct it if you can
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 questionAsk a Question
731 491 924 answers to any question