本文介绍了Django - 为什么syncdb不尊重数据库路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了数据库路由器,使用 db_for_read db_for_write 路由器方法。



除非 ./ manage.py syncdb 不尊重路由器设置。



当我 syncdb 我的模型,它们都是在默认数据库中创建的。 >

数据库路由器只提供一个 allow_syncdb 方法,但没有 sync_to 方法。有没有办法告诉 syncdb 命令在哪里创建新表?



注意: / strong>我不能使用 - 数据库功能,有时一些模型应用程序会转到不同于其他应用程序的数据库。

解决方案

当您编写路由器时,请确保已经写了allow_syncdb()方法。它同时使用数据库和模型。当您运行 manage.py syncdb 时,您基本上设置了 - database = default 。如果您不想将模型同步到默认数据库,那么allow_syncdb()方法应该返回False,条件是 db == default和model._meta.app_label == myapp



您需要使用 - database = your_other_db 选项运行syncdb才能获取 myapp 到该数据库。但是在这种情况下,请确保allow_syncdb()仅在 db == your_other_db和model._meta.app_label == myapp 的情况下返回True。



这是否有意义?基本上你必须为每个数据库一次运行 manage.py syncdb 方法两次。您只能运行一次,并且可以更新这两个数据库。


I have set up a database router to direct different apps and different models to different databases using the db_for_read and db_for_write router methods.

That works very well, except that ./manage.py syncdb does't respect those router settings.

When I syncdb my models, all of them are created in the default database.

The database router only provides an allow_syncdb method, but no sync_to method. Is there a way to tell the syncdb command where to create the new tables?

Note: I can't use the --database feature, as sometimes some of the model apps go to a different database than the rest of the app.

解决方案

When you write your router make sure you've written the allow_syncdb() method. It takes both a database and a model. When you run manage.py syncdb you're essentially setting the --database=default. If you don't want your models to sync to the default database then your allow_syncdb() method should return False for the condition that db==default and model._meta.app_label==myapp.

You'll need to run syncdb with the --database=your_other_db option to get myapp into that db. But make sure in that case that allow_syncdb() returns True only for the case that db==your_other_db and model._meta.app_label==myapp.

Does that make sense? Basically you have to run the manage.py syncdb method twice, once for each database. You cannot run it only once and have it update both databases.

这篇关于Django - 为什么syncdb不尊重数据库路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 03:27