Ir para o conteúdo
ou

Software livre Brasil

0 amigos

Nenhum(a)

0 comunidades

Nenhum(a)

Diego Búrigo Zacarão

 Voltar a Blog em dieg...
Tela cheia

Django Database Router using settings

10 de Fevereiro de 2011, 0:00 , por Software Livre Brasil - 0sem comentários ainda | Ninguém está seguindo este artigo ainda.
Visualizado 263 vezes

It’s been a while without passing here… but let’s not talk about it! :)

So, this week I just came across an issue related to how to setup multiple databases on Django. Reading the documentation I found it quite trivial to setup. After having the databases configured, you can use a Database Router, if you want to automatically route your app models, or use .using(‘db1′) manually on your queries, specifying the wanted database.

As I didn’t want to specify the databases on the queries in my code, so I decided to use the Database Router, which is, by the way, a very nice solution for such a problem. Looking at the example on the Django docs, I realized that the example was only covering the routing of an unique app. Looking further, I also noticed that it was a bit tied with placeholders related to the app and the database names inside the class. Then I asked myself:

Couldn’t it be more generic and reusable for more than one app?

Searching a bit on the Web I couldn’t find anything. Having that in mind, I came with the following code that can be used to specify several apps using different databases. Everything just using a single settings variable and in a very simple way:

from django.conf import settings

class DatabaseAppsRouter(object):
    """
    A router to control all database operations on models for different
    databases.

    In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
    will fallback to the `default` database.

    Settings example:

    DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
    """

    def db_for_read(self, model, **hints):
        """"Point all read operations to the specific database."""
        if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
            return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
        return None

    def db_for_write(self, model, **hints):
        """Point all write operations to the specific database."""
        if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
            return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """Allow any relation between apps that use the same database."""
        db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label)
        db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label)
        if db_obj1 and db_obj2:
            if db_obj1 == db_obj2:
                return True
            else:
                return False
        return None

    def allow_syncdb(self, db, model):
        """Make sure that apps only appear in the related database."""
        if db in settings.DATABASE_APPS_MAPPING.values():
            return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db
        elif settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
            return False
        return None

I hope the code can self explain what each one of those methods do. And, of course, it’s a generic solution that might be customized as needed. :)


Fonte: http://diegobz.net/2011/02/10/django-database-router-using-settings/

0sem comentários ainda

Enviar um comentário

Os campos são obrigatórios.

Se você é um usuário registrado, pode se identificar e ser reconhecido automaticamente.