使用multidb路由器,如何将所有django_ *表(模型)移动到另一个db而不是默认值(同时移动django_migrations表)?
通过“移动”,我接受简单地将它们放在另一个数据库中
编辑:好的,似乎django_migration无法移动并且存在于每个数据库......
但是使用该代码,我收到一个奇怪的错误:
网/ settings.py:
DATABASES = {
'intern_db': {
'ENGINE': 'mysql.connector.django',
'NAME': 'django_cartons',
'USER': 'root',
'PASSWORD' : '',
},
'default': {
'ENGINE': 'mysql.connector.django',
'NAME': 'carton2',
'USER': 'root',
'PASSWORD' : '',
}
}
DATABASE_ROUTERS = ['web.AuthRouter.AuthRouter']
网/ AuthRouter.py
class AuthRouter(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.
"""
if model._meta.app_label == 'auth':
return 'intern_db'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth.
"""
if model._meta.app_label == 'auth':
return 'intern_db'
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'auth' or \
obj2._meta.app_label == 'auth':
return True
return None
def allow_migrate(self, db, model):
"""
Make sure the auth app only appears in the 'auth'
database.
"""
return False
if db == 'intern_db':
return (model._meta.app_label == 'auth')
elif model._meta.app_label == 'auth':
return False
return None
错误:
$> ./manage.py migrate
Operations to perform:
Apply all migrations: contenttypes, admin, auth, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial...Traceback (most recent call last):
File "/usr/lib/python3.4/site-packages/mysql/connector/django/base.py", line 115, in _execute_wrapper
return method(query, args)
File "/usr/lib/python3.4/site-packages/mysql/connector/cursor.py", line 507, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/lib/python3.4/site-packages/mysql/connector/connection.py", line 722, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/lib/python3.4/site-packages/mysql/connector/connection.py", line 640, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 1005 (HY000): Can't create table `carton2`.`#sql-c20_10d` (errno: 150 "Foreign key constraint is incorrectly formed")
答案 0 :(得分:0)
如上所述,您必须通过--database
选项来选择数据库。
实际上,将django表放在另一个数据库中而不是默认值是不错的选择,因为其他应用程序假设这些表是默认的。此外,还有一个"迁移"表自动创建django所需的表。