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
- New Snippet! by Antoliny0919 3 days, 13 hours ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
- get_object_or_none by azwdevops 6 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 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.