【发布时间】:2018-12-19 17:09:39
【问题描述】:
我在我的 django 项目中创建了两个数据库,一个应用程序将其数据写入一个数据库,第二个 - 另一个。但是当我进行迁移时,两个应用程序的所有模型都会在两个数据库中创建它们的表,尽管它们仍然是空的(每个表中只有一个空行)
是否可以告诉 Django(Django,不要这样做=)不要在两个数据库中创建我不需要的额外表?
这是我的代码
routers.py
from django.conf import settings
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
if model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return None
def allow_relation(self, obj1, obj2, **hints):
"""Allow any relation between apps that use the same database."""
db_obj1 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label)
db_obj2 = settings.DATABASE_APPS_MAPPING.get(obj2._meta.app_label)
if db_obj1 and db_obj2:
if db_obj1 == db_obj2:
return True
else:
return False
return None
def allow_syncdb(self, db, model):
"""Make sure that apps only appear in the related database."""
if db in settings.DATABASE_APPS_MAPPING.values():
return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db
elif model._meta.app_label in settings.DATABASE_APPS_MAPPING:
return False
return None
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'tracking_db': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'tracking',
'USER': 'root',
'PASSWORD': '12345678',
}
}
DATABASE_APPS_MAPPING = {
'contenttypes': 'default',
'auth': 'default',
'admin': 'default',
'sessions': 'default',
'messages': 'default',
'staticfiles': 'default',
'news': 'default',
'tracking': 'tracking_db',
}
DATABASE_ROUTERS = ['newswallproj.routers.DatabaseAppsRouter']
models.py
Model here
class Meta:
app_label = 'tracking'
【问题讨论】: