搜了很多文章,感觉这篇说得最清楚。


官方文档 https://docs.djangoproject.com/en/1.4/topics/db/multi-db/ 描述

本文仅仅描述使用router的方法,这里以一个汉字拼音数据库为例

1首先在settings.py 文件中添加多个数据库


DATABASES = {
    'default': 
    {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'default',                      # Or path to database file if using sqlite3.
        'USER': 'xxx',                      # Not used with sqlite3.
        'PASSWORD': 'xxx',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },
    'pinyin':
    {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'pinyin',                      # Or path to database file if using sqlite3.
        'USER': 'xxx',                      # Not used with sqlite3.
        'PASSWORD': 'xxx',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },    
             
}



2定义models


class pinyin(models.Model):
    _database = 'pinyin'
    charact = models.CharField(max_length=4)
    pinyin = models.CharField(max_length=10)
    onset = models.CharField(max_length=2)  
    rime = models.CharField(max_length=4)   
    ucode = models.IntegerField()           
    freq = models.IntegerField()



其中模型 pinyin 有一个额外的属性 _database,他说明了模型将要连接的数据库。如果没有这个属性,我们默认为他的值为default,即使默认的数据库 。

3 编写router

router有四个方法,


def db_for_read(self, model, **hints)   建议 model 对象读操作时使用的数据库。
def db_for_write(self, model, **hints)   建议 model 对象写操作时使用的数据库。
def allow_relation(self, obj1, obj2, **hints) 当 obj1 和 obj2 之间允许有关系时返回 True ,不允许时返回 False ,或者没有 意见时返回 None 。
def allow_syncdb(self, db, model)  决定 model 是否可以和 db 为别名的数据库同步。



class AppRouter(object):
    def db_for_read(self, model, **hints):
        if hasattr(model, '_database'):
            return model._database
        return 'default'

    def db_for_write(self, model, **hints):
        if hasattr(model, '_database'):
            return model._database
        return  'default'


    def allow_relation(self, obj1, obj2, **hints):

        return None

    def allow_syncdb(self, db, model):
        if hasattr(model, '_database'):
            model_db = model._database
        else:
            model_db = 'default'
            
        if db == model_db:
            return True
        else:
            return False


4向settings.py中添加 DATABASE_ROUTERS 


DATABASE_ROUTERS = ['path.to.AppRouter']


现在就完成了。



在进行syncdb操作的时候,要注意syncdb有一个参数--database=dbase,其中dbase默认值是default,即默认是同步到default数据库。
在syncdb的时候,就要询问AppRouter的 allow_syncdb(self, db, model)方法,其中db就是参数dBase,model就是要同步的模型。返回True就是可以,False就是拒绝,None是不管。
对于有多个数据库时候,就需要syncdb多次,每一次同步一个数据库,就可以完成了。