Login

Model-driven multiple database router

Author:
tga
Posted:
February 14, 2012
Language:
Python
Version:
1.3
Tags:
multiple-databases routing
Score:
1 (after 1 ratings)

Multiple database router that allows setting the target database for each model by setting the in_db field in its Meta class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# >>> in models.py >>>

# Add recognized model option to django
import django.db.models.options as options
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('in_db',)

# <<<

# >>> in routers.py >>>

class ModelDatabaseRouter(object):
    """Allows each model to set its own destiny"""
    
    def db_for_read(self, model, **hints):
        # Specify target database with field in_db in model's Meta class
        if hasattr(model._meta, 'in_db'):
            return model._meta.in_db
        return None

    def db_for_write(self, model, **hints):
        # Specify target database with field in_db in model's Meta class
        if hasattr(model._meta, 'in_db'):
            return model._meta.in_db        
        return None
    
    def allow_syncdb(self, db, model):      
        # Specify target database with field in_db in model's Meta class
        if hasattr(model._meta, 'in_db'):
            if model._meta.in_db == db:
                return True
            else:
                return False
        else:
            # Random models that don't specify a database can only go to 'default'
            if db == 'default':
                return True
            else:
                return False

# <<<

More like this

  1. Manager for multiple database connections by rix 6 years ago
  2. Persistent connection to PostgreSQL database by mike_tk 6 years ago
  3. Forcing DB on relationship manager with multiple database project by ryananguiano 9 months, 3 weeks ago
  4. Serve multiple hostnames with different URLCONF's from one Django instance by rmt 6 years, 3 months ago
  5. Multiple User subclasses custom Auth backend by ungenio41 3 years, 11 months ago

Comments

jose_lpa (on July 19, 2012):

Nice hack! Very useful. That 'in_db' field of models Meta class should be implemented in Django core.

#

danohuiginn (on October 22, 2012):

unless I'm missing something, most of those methods could be streamlined to:

return getattr(model._meta, 'in_db', None)

Useful approach, though

#

mark305 (on November 11, 2013):

This is really useful, but doesn't this defeat the object of de-coupling in Django?

#

Please login first before commenting.