0

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
cph
  • 458
  • 2
  • 6
  • 24

2 Answers2

0

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']
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

You need different setting files. Add local.py under settings. Then run python

manage.py syncdb --settings=project.settings.local

See the most voted answer here: How to manage local vs production settings in Django?

Community
  • 1
  • 1
François Constant
  • 5,531
  • 1
  • 33
  • 39