我有一个名为xyz.com的域名运行带有数据库的django项目。我有另一个Django项目应该指向xyz.com/pray与不同的数据库。是否可以这样做?
答案 0 :(得分:2)
项目/ urls.py:
urlpatterns = patterns('',
...
url(r'^pray/', include('prayapp.urls')), # all of this apps ulrs start with /pray
url(r'^', include('otherapp.urls')), # all of these urls start at the root /
...
)
和https://docs.djangoproject.com/en/1.3/topics/db/multi-db/#an-example:
数据库设置:
DATABASES = {
# for the rest of your project
'default': {
'NAME': 'app_data',
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'USER': 'postgres_user',
'PASSWORD': 's3krit'
},
# for your prayapp
'other': {
'NAME': 'user_data',
'ENGINE': 'django.db.backends.mysql',
'USER': 'mysql_user',
'PASSWORD': 'priv4te'
}
}
自定义路由器:
class PrayAppRouter(object):
"""A router to control all database operations on models in
the prayapp application"""
def db_for_read(self, model, **hints):
"Point all operations on prayapp models to 'other'"
if model._meta.app_label == 'prayapp':
return 'other'
return None
def db_for_write(self, model, **hints):
"Point all operations on prayapp models to 'other'"
if model._meta.app_label == 'prayapp':
return 'other'
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in prayapp is involved"
if obj1._meta.app_label == 'prayapp' or obj2._meta.app_label == 'prayapp':
return True
return None
def allow_syncdb(self, db, model):
"Make sure the prayapp app only appears on the 'other' db"
if db == 'other':
return model._meta.app_label == 'prayapp'
elif model._meta.app_label == 'prayapp':
return False
return None
将此添加到您的settings.py
DATABASE_ROUTERS = ['path.to.PrayAppRouter',]