Django - Why doesn't syncdb respect the databa

2019-07-07 01:32发布

问题:

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.

回答1:

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.