我创建了一个django项目,然后创建了两个应用程序app1和app2。我希望这两个应用程序共享一个mysql数据库(mysql的名称DB,django的名称mydb)。我在settings.py中将数据库添加到了DATABASES,并为每个应用程序创建了一个dbrouter文件,并将每个路由器添加到database_ROUTERS。同样在settings.py中,将每个应用程序添加到INSTALLED_APPS。
我的问题是当我试图
python manage.py syncdb --database=mydb
因为它不会同步两个应用程序(只有app1)。上面写着:
Creating tables ...
Creating table app1_model1
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
这里是我的设置.py:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app1',
'app2',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'mydb':{
'ENGINE': 'django.db.backends.mysql',
'NAME': 'nameofDB',
'USER':'username',
'PASSWORD':'password',
}
}
DATABASE_ROUTERS = ['app1.dbRouter.App1DBRouter', 'app2.dbRouter.App2DBRouter']
这里是我的模型:
app1/型号.py:
class Model1(models.Model):
name = models.CharField(max_length=100)
app2/型号.py:
class Model2(models.Model):
name = models.CharField(max_length=100)
这是我的数据库路由器
app1/dbRouter.py
class App1DBRouter(object):
def db_for_read(self,model, **hints):
if model._meta.app_label == 'app1':
return 'mydb'
return None
def db_for_write(self,model, **hints):
if model._meta.app_label == 'app1':
return 'mydb'
return None
def allow_relation(self,obj1, obj2, **hints):
if obj1._meta.app_label == 'app1' and \
obj2._meta.app_label == 'app1':
return True
return None
def allow_syncdb(self,db, model):
if db == 'mydb':
return model._meta.app_label == 'app1'
elif model._meta.app_label == 'app1':
return False
return None
app2/dbRouter.py
class App2DBRouter(object):
def db_for_read(self,model, **hints):
if model._meta.app_label == 'app2':
return 'mydb'
return None
def db_for_write(self,model, **hints):
if model._meta.app_label == 'app2':
return 'mydb'
return None
def allow_relation(self,obj1, obj2, **hints):
if obj1._meta.app_label == 'app2' and \
obj2._meta.app_label == 'app2':
return True
return None
def allow_syncdb(self,db, model):
if db == 'mydb':
return model._meta.app_label == 'app2'
elif model._meta.app_label == 'app2':
return False
return None
它怎么了?我该怎么办?提前感谢!:)