Model-driven multiple database router

 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 4 years, 8 months ago
  2. Persistent connection to PostgreSQL database by mike_tk 4 years, 7 months ago
  3. Serve multiple hostnames with different URLCONF's from one Django instance by rmt 4 years, 11 months ago
  4. Multiple User subclasses custom Auth backend by ungenio41 2 years, 7 months ago
  5. Database Routing by URL by dcwatson 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?

#

(Forgotten your password?)