对于Django中的一个项目,我必须使用两个数据库:default和remote。我已经创建了routers.py
,一切正常。在
需要在远程数据库上创建一个表,我创建了migration,运行它,然后创建了表django_migrations
。我希望在默认数据库中只有一个表django_migrations
。在
routers.py
的相关部分如下:
class MyRouter(object):
# ...
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label == 'my_app':
return db == 'remote'
return None
我是这样运行迁移的:
^{pr2}$现在当我这么做的时候:
python manage.py runserver
我得到以下警告:
You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): my_app.
Run 'python manage.py migrate' to apply them.
my_app
的表是在remote
数据库中创建的,在remote
数据库内的django_migrations
中,迁移被标记为已应用。在
编辑:
如何强制Django只使用一个表django_migrations
,但仍然将迁移应用到不同的数据库中?
如何在不同的数据库中应用迁移,以便不发出警告?在
多亏了对我问题的评论,我做了一些研究,得出了以下结论。在
使用多个数据库会导致在使用迁移时创建一个表} 之后就清楚了。在
django_migrations
。正如来自Kamil Niski的注释所解释的那样,没有选项只在一个表django_migrations
中记录迁移。这在读取文件^{我将用一个项目
foo
和项目内的一个应用程序bar
来举例说明。应用程序bar
只有一个型号Baz
。在我们创建项目:
现在在主项目目录中有以下内容:
^{pr2}$我习惯于将项目目录中的所有应用程序分组:
在文件
foo/settings.py
中,我们调整设置以使用两个不同的数据库,在本例中,我们使用sqlite3
:现在我们运行迁移:
这将运行所有迁移,而
database=default
部分是可选的,因为如果没有指定,Django将使用默认数据库。在Django已将所有迁移应用到默认数据库:
现在我们创建模型
Baz
:models.py
:将应用程序
bar
注册到INSTALLED_APPS
(foo/settings.py
)并创建迁移:在运行迁移之前,我们在
bar
应用程序中创建routers.py
:并将其注册到
foo/settings.py
:现在,简单的方法是将
bar
迁移到remote
数据库中:迁移已应用于
remote
数据库:当我们跑步时:
将发出以下警告:
不过,一切似乎都很好。然而,有这个警告并不令人满意。在
正确的方法是按照这个answer中的建议为每个数据库运行所有迁移。在
它看起来像这样:
在为
bar
创建迁移之后:路由器将注意表
bar_baz
只在remote
数据库中创建,但Django将标记迁移,使其应用于这两个数据库。另外,auth
、admin
、sessions
等的表将仅在default
数据库中创建,如routers.py
中所指定。remote
数据库中的表django_migrations
也将有这些迁移的记录。在这是一个很长的阅读,但我希望它能对这一点有所启示,我认为官方没有对这个问题进行彻底的解释。在
相关问题 更多 >
编程相关推荐