predator
predator

Reputation: 477

Setting models to specific database in django

I would like to ask how to set models to specific database . I'm still new to django and read about the Database Routing in the Django website, I have 2 models, userMod and adminMod.
userMod should go to database userDB.
adminMod should go to database adminDB.
But when I migrated it, both table exist in both database. I already have included app_label on meta, but its still not working. I am using django 1.8


EDIT: I am just trying it on userDB for a while and eventually will use it with adminDB. This is my code:

routers.py

class router(object):

def db_for_read(self, model, **hints):
    if model._meta.app_label == 'userDB':
        return 'userDB'
    return None

def db_for_write(self, model, **hints):
    if model._meta.app_label == 'userDB':
        return 'userDB'
    return None

def allow_relation(self, obj1, obj2, **hints):
    if obj1._meta.app_label == 'userDB' or\
        obj2._meta.app_label == 'userDB':
            return True
        return None

def allow_migrate(self, db, app_label, model=None, **hints):
    if app_label == 'userDB':
        return db == 'userDB'
    return None

Upvotes: 2

Views: 1338

Answers (2)

Tony Dare
Tony Dare

Reputation: 301

Remember to tell django about your database router in the settings.py

https://docs.djangoproject.com/en/1.8/topics/db/multi-db/

Search for DATABASE_ROUTERS setting

Upvotes: 1

Geo Jacob
Geo Jacob

Reputation: 6009

Try this:

class userMod(models.Model):
   name = models.CharField(max_length=120)

   class Meta:
      db_table='userDB'

Upvotes: 1

Related Questions