3.2. Settings Databases
3.2.1. SetUp
>>> import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
>>> import django; django.setup()
>>>
>>> from shop.models import Customer, Address, Order
3.2.2. SQLite3
>>>
... DATABASES = {
... 'default': {
... 'ENGINE': 'django.db.backends.sqlite3',
... 'NAME': BASE_DIR / 'db.sqlite3',
... }
... }
3.2.3. PostgreSQL
>>>
... DATABASES = {
... 'default': {
... 'ENGINE': 'django.db.backends.postgresql',
... 'NAME': 'myproject',
... 'USER': 'myusername',
... 'PASSWORD': 'mypassword',
... 'HOST': 'localhost',
... 'PORT': 5432,
... }
... }
3.2.4. Heroku
>>>
... if os.getenv('DATABASE_URL'):
... import dj_database_url
... DATABASES['default'] = dj_database_url.config()
3.2.5. Multiple Databases
File: myproject/settings.py
>>>
... DATABASES = {
... 'default': {
... 'ENGINE': 'django.db.backends.postgresql',
... 'NAME': 'myproject',
... 'USER': 'myusername',
... 'PASSWORD': 'mypassword',
... 'HOST': '192.168.0.2',
... 'PORT': 5432,
... },
... 'other': {
... 'ENGINE': 'django.db.backends.postgresql',
... 'NAME': 'myproject',
... 'USER': 'myusername',
... 'PASSWORD': 'mypassword',
... 'HOST': '192.168.0.3',
... 'PORT': 5432,
... }
... }
Then you can use ORM:
>>> Project.objects.using('other').all()
If you don't want to add .using('other')
to each ORM
query, you can create a database router file with dispatcher.
Also remember to configure DATABASE_ROUTERS
in your
myproject/settings.py
:
File: myproject/settings.py
>>> DATABASE_ROUTERS = ['myproject.db_router.MyDatabaseRouter']
File myproject/db_router.py
:
>>>
... class MyDatabaseRouter:
... ecosystem = ['confluence', 'jira', 'bitbucket', 'bamboo']
...
... def db_for_read(self, model, **hints):
... if model._meta.app_label in self.ecosystem:
... return model._meta.app_label
... else:
... return 'default'
...
... def db_for_write(self, model, **hints):
... return 'default'
...
... def allow_relation(self, obj1, obj2, **hints):
... if obj1._meta.app_label in self.ecosystem:
... return False
... elif obj2._meta.app_label in self.ecosystem:
... return False
... return True
...
... def allow_syncdb(self, db, model):
... if model._meta.app_label in self.ecosystem:
... return False
... else:
... return True