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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Nice hack! Very useful. That 'in_db' field of models Meta class should be implemented in Django core.
#
unless I'm missing something, most of those methods could be streamlined to:
Useful approach, though
#
This is really useful, but doesn't this defeat the object of de-coupling in Django?
#
Please login first before commenting.