-3

我有一个名为 xyz.com 的域,它运行一个带有数据库的 django 项目。我有另一个 Django 项目,它应该指向 xyz.com/pray 和不同的数据库。有可能这样做吗?

4

1 回答 1

2

是的,我会看两件事:

  1. 用于您的一个应用程序的数据库路由器
  2. 每个应用程序的 urls.py 文件

项目/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',]
于 2012-06-25T19:26:27.157 回答