我正在尝试在我的django项目中设置芹菜。我希望芹菜使用一个单独的数据库。目前,由于项目处于开发阶段,我们使用的是sqlite3。为了设置多个数据库,我做了以下工作。
DATABASES = {'default':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME':'devel',
'USER':'',
'PASSWORD':'',
'HOST':'',
'PORT':'',
},
'celery':
{'ENGINE': 'django.db.backends.sqlite3',
'NAME':'celery',
'USER':'',
'PASSWORD':'',
'HOST':'',
'PORT':'',
},
}
class CeleryRouter(object):
"""
This class will route all celery related models to a»
separate database.
"""
# Define the applications to be used in the celery database
APPS = (
'django',
'djcelery'
)
# Define Database Alias
DB = 'celery'
def db_for_read(self, model, **hints):
"""
Point read operations to celery database.
"""
if model._meta.app_label in self.APPS:
return self.DB
return None
def db_for_write(self, model, **hints):
"""
Point write operations to celery database.
"""
if model._meta.app_label in self.APPS:
return self.DB
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow any relation between two objects in the db pool
"""
if (obj1._meta.app_label is self.APPS) and \
(obj2._meta.app_label in self.APPS):
return True
return None
def allow_syncdb(self, db, model):
"""
Make sure the celery tables appear only in celery
database.
"""
if db == self.DB:
return model._meta.app_label in self.APPS
elif model._meta.app_label in self.APPS:
return False
return None
DATABASE_ROUTER
变量DATABASE_ROUTERS = [
'appname.db_routers.CeleryRouter',
]
现在,当我python manage.py syncdb
时,我看到表是为芹菜创建的,但只创建了一个数据库,即devel
。为什么表是在devel
数据库中而不是在celery
数据库中创建的?
答案 0 :(得分:2)
引自Django docs:
syncdb管理命令一次在一个数据库上运行。默认情况下,它在默认数据库上运行,但通过提供--database参数,您可以告诉syncdb同步另一个数据库。
尝试跑步:
./manage.py syncdb --database=celery