Django 多應用多數據庫

  1. settings.py:


    DATABASES = {

       'default': {

            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.

            'NAME': 'test',                      # Or path to database file if using sqlite3.

            'USER': 'test',                      # Not used with sqlite3.

            'PASSWORD': 'test',                  # Not used with sqlite3.

            'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.

            'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.

        },

        'user': {

            'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.

            'NAME': 'userdb',                      # Or path to database file if using sqlite3.

            'USER': 'user',                      # Not used with sqlite3.

            'PASSWORD': 'user',                  # Not used with sqlite3.

            'HOST': '10.58.**.**',                      # Set to empty string for localhost. Not used with sqlite3.

            'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.

        }

    }

    DATABASE_ROUTERS = ['dbsettings.appdb']

  2. 實現自己的DB routers,這裏決定了每個應用使用的是哪個DB

    dbsettings.py:


    class appdb(object):

     

        def db_for_read(self, model, **hints):

            #該方法定義讀取時從哪一個數據庫讀取

            return self.__app_router(model)

     

        def db_for_write(self, model, **hints):

            #該方法定義寫入時從哪一個數據庫讀取,如果讀寫分離,可再額外配置

            return self.__app_router(model)

     

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

            #該方法用於判斷傳入的obj1和obj2是否允許關聯,可用於多對多以及外鍵

            #同一個應用同一個數據庫

            if obj1._meta.app_label == obj2._meta.app_label:

                return True

            #User和Essay是允許關聯的

            elif obj1._meta.app_label in ('userApp','essayApp') and

            #接上一行  obj2._meta.app_label in ('userApp','essayApp'):

                return True

     

     

        def allow_syncdb(self, db, model):

            #該方法定義數據庫是否能和名爲db的數據庫同步

            return self.__app_router(model) == db

     

       #添加一個私有方法用來判斷模型屬於哪個應用,並返回應該使用的數據庫

        def __app_router(self, model):

            if model._meta.app_label == 'user':

                return 'userdb'

            else :

                return 'default'

  3. 使用方法

    User.objects.using('user').all()

    python manage.py syncdb --database=user

  4. 自定義sql:


     from django.db import connections

      

cursor = connections[‘user’].cursor()

    sql="select *  user"

    cursor.execute(sql)

    rows = cursor.fetchall()

    return render_to_response('index.html',locals())


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章