V
V
V2016-09-23 13:02:57
Django
V, 2016-09-23 13:02:57

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='Клипы'

In the Clip class, I explicitly write that this is saved to a table in a specific database. Also I wrote Router
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

and registered in settings.py
DATABASE_ROUTERS = ['path_to_router.ClipRouter'] #путь у меня нормальный, тут просто поменял

As a result, when you try to save the clip, it is saved to the database, but instead an exception pops up on the ecarne that there is no table. That is, he is trying to save the default database table, where it does not physically exist.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2016-09-23
@ermolushka

Try to check not app_label, but the name of the class prayed. Well, no one canceled debugging - pdb or at least prints.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question