Login

Model-driven multiple database router

Author:
tga
Posted:
February 14, 2012
Language:
Python
Version:
1.3
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.