Django Multiple Database
Django 데이터베이스 여러개 사용하기
Database Router를 구현하고, 모델에서는 라우터를 지정하기만 하면 된다.
Since Django 1.2, you can define multiple datbase connections in your settings.py
. Then you can use database routers to tell Django which database to go to, transparently for your application.
Disclaimer: this is how I think it should work, I have never used MongoDB in Django, nor have I tested that my code actually works. :)
settings.py
DATABASES = {
'default': {
'ENGINE': 'django_mongodb_engine',
'NAME': 'mydata',
...
}
'geodata' {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'geodata',
...
}
}
DATABASE_ROUTERS = ['path.to.ModelMetaRouter']
Models
Then add custom Meta variables to your geo-tables, to override their database. Don't add this attribute to models that are supposed to go to the default database.
class SomeGeoModel(models.Model):
...
class Meta:
using = 'geodata'
Database router
And write a database router to direct all models that have the using
meta attribute set, to the appropriate connection:
class ModelMetaRouter(object):
def db_for_read(self, model, **hints):
return getattr(model._meta, 'using', None)
def db_for_write(self, model, **hints):
return getattr(model._meta, 'using', None)
def allow_relation(self, obj1, obj2, **hints):
# only allow relations within a single database
if getattr(obj1._meta, 'using', None) == getattr(obj2._meta, 'using', None):
return True
return None
def allow_syncdb(self, db, model):
if db == getattr(model._meta, 'using', 'default'):
return True
return None
http://stackoverflow.com/a/5757011/2050087
'WebDev' 카테고리의 다른 글
django CSRF disable (CSRF 해제) (0) | 2016.01.20 |
---|---|
django class-based view (0) | 2016.01.15 |
Django Url (0) | 2016.01.14 |
Django Deploy (0) | 2016.01.04 |
Django settings 값 가져오기 (0) | 2015.11.15 |