你必须像这样在 settings.py 文件中指定你的数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
'postgresql': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'myproject',
'USER': 'myprojectuser',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '',
}
}
然后,在您的项目文件夹中,您可以创建一个名为:routersGlobal.py
的文件
from django.conf import settings
class GlobalRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth.
"""
app_list = ('auth', 'admin', 'contenttypes', 'sessions',)
if model._meta.app_label in app_list:
return 'default' #According to database name sqlite3
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth.
"""
app_list = ('auth', 'admin', 'contenttypes', 'sessions',)
if model._meta.app_label in app_list:
return 'default'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
app_list = ('auth', 'admin', 'contenttypes', 'sessions',)
if obj1._meta.app_label in app_list and obj2._meta.app_label in app_list:
return True
return None
def allow_migrate(self, db, app_label, model=None, **hints):
"""
Make sure the auth app only appears in the 'auth'
database.
"""
app_list = ('auth', 'admin', 'contenttypes', 'sessions',)
if app_label in app_list:
return db == 'default'
return None
您可以创建一个名为 routersLocal.py 的文件:
from django.conf import settings
class LocalRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth.
"""
app_list = ('YourNewApp',)
if model._meta.app_label in app_list:
return 'postgresql'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth.
"""
app_list = ('YourNewApp',)
if model._meta.app_label in app_list:
return 'postgresql'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
app_list = ('YourNewApp',)
if obj1._meta.app_label in app_list and obj2._meta.app_label in app_list:
return True
return None
def allow_migrate(self, db, app_label, model=None, **hints):
"""
Make sure the auth app only appears in the 'auth'
database.
"""
app_list = ('YourNewApp',)
if app_label in app_list:
return db == 'postgresql'
return None
最后在 settings.py 文件中你必须指定重定向:
DATABASE_ROUTERS = ['YourProjectName.routersLocal.LocalRouter', 'YourProjectName.routersGlobal.GlobalRouter']
然后,它应该可以工作并应用分离迁移