- Define database connections in myproject/settings.py:
DATABASES = { 'default': { 'NAME': 'db1', 'ENGINE': 'django.db.backends.mysql', 'USER': 'myuser1', 'PASSWORD': 'mypass1', }, 'my_db_2': { 'NAME': 'db2', 'ENGINE': 'django.db.backends.mysql', 'USER': 'myuser2', 'PASSWORD': 'mypass2' } }
- Define router in myproject/myapp2/routers.py:
class MyApp2Router(object): """ A router to control all database operations on models in the myapp2 application """ def db_for_read(self, model, **hints): """ Point all operations on myapp2 models to 'my_db_2' """ if model._meta.app_label == 'myapp2': return 'my_db_2' return None def db_for_write(self, model, **hints): """ Point all operations on myapp models to 'other' """ if model._meta.app_label == 'myapp2': return 'my_db_2' return None def allow_syncdb(self, db, model): """ Make sure the 'myapp2' app only appears on the 'other' db """ if db == 'my_db_2': return model._meta.app_label == 'myapp2' elif model._meta.app_label == 'myapp2': return False return None
This is pretty much a copy and paste job from the official example. The one key point left out was where to define this. It turns out that myapp2/models.py is not the right place and something like myapp2/routers.py is! - Now all that remains is to tell our project about the router. In myproject/settings.py add:
DATABASE_ROUTERS = ['myapp.routers.MyApp2Router',]
Multiple database implementation in Django
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment