Answer the question
In order to leave comments, you need to log in
How to work with multiple databases in Django?
Hello. In settings.py I use two bases: 'default' and 'admin_site'.
models.py
class Project(models.Model):
name = models.CharField(max_length=256, verbose_name='Название проекта')
def __str__(self):
return "%s" % self.name
class Meta(object):
db_table='project'
verbose_name = 'Проект'
verbose_name_plural = 'Проекты'
class Clip(models.Model):
name = models.TextField('Название', max_length=1000, blank=True)
description = models.TextField('Описание', max_length=10000, blank=True)
date = models.DateTimeField('Дата создания фильма', default=datetime.now())
def __str__(self):
return "%s" % self.name
def save(self, force_insert=False, force_update=False, using='admin_site'):
return super(Clip, self).save(using=using)
class Meta(object):
db_table='clip'
verbose_name='Клип'
verbose_name_plural='Клипы'
class ClipRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.app_label == 'clip':
return 'admin_site'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.app_label == 'clip':
return 'admin_site'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'clip' or \
obj2._meta.app_label == 'clip':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if app_label == 'clip':
return db == 'admin_site'
return None
DATABASE_ROUTERS = ['path_to_router.ClipRouter'] #путь у меня нормальный, тут просто поменял
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question