pythondjangosyncdb

How do I stop Django "python manage.py syndb" from adding tables to multiple DB's in Settings?


I have two databases configured in settings.py, the default one and another called "local_mysql".

I want to create a model such that when I do python manage.py syncdb it is only populated in the local_mysql database. How is this possible?

I couldn't find much searching around.


Solution

  • You need to implement a database router, as detailed in the documentation:

    If you don’t want every application to be synchronized onto a particular database, you can define a database router that implements a policy constraining the availability of particular models.

    To define your router, its just a class with some methods:

    class MyRouter(object):
    
        def db_for_read(self, model, **hints):
            if model._meta.app_label == 'yourappname':
                return 'local_mysql'
            return None
    
        def db_for_write(self, model, **hints):
            return self.db_for_read(model, **hints)
    
        def allow_relation(self, obj1, obj2, **hints):
            if obj1._meta.app_label == 'yourappname' or \
               obj2._meta.app_label == 'yourappname':
               return True
            return None
    
        def allow_migrate(self, db, model):
            if db == 'local_mysql':
                return model._meta.app_label == 'yourappname'
            elif model._meta.app_label == 'yourappname':
                return False
            return None
    

    Put this class in a file called routers.py in the same location as views.py for your app, for which you want to redirect the database.

    Then, in settings.py, add the following:

    DATABASE_ROUTERS = ['yourappname.routers.MyRouter']