1. 程式人生 > >django資料庫分庫migrate

django資料庫分庫migrate

最近在研究微服務和分散式,設計到了資料庫分庫,記錄一下 首先,建立多個數據庫,如果是已經生成的資料庫,可以分庫,這裡我是新建立的專案,剛好可以用來嘗試 我是用docker建立的mysql資料庫容器 拉取docker映象: `docker pull mysql:5.7` 建立容器: `docker run --name=mysql5.7 -p 13306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.7` 建立多個mysql容器之後,django配置好相應資料庫,我這裡分成了三個資料庫,一個是預設,放django的user,group,permission,session之類的,另外一個是order和sale兩個app的,這裡我打算下一步微服務的時候再拆開,這裡先記錄分庫的事情,資料庫程式碼如下: ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '192.168.1.112', 'PORT': '13308', 'NAME': 'default', 'USER': 'root', 'PASSWORD': '0123456789', 'TEST': { 'MIRROR': 'default' } }, 'sale': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '192.168.1.112', 'PORT': '13306', 'NAME': 'sale', 'USER': 'root', 'PASSWORD': '0123456789', 'TEST': { 'MIRROR': 'default' } }, 'order': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '192.168.1.112', 'PORT': '13307', 'NAME': 'order', 'USER': 'root', 'PASSWORD': '0123456789', 'TEST': { 'MIRROR': 'default' } } } ``` 分庫之後,在settings.py同級目錄下,建立一個databaserouter ``` DATABASE_MAPPING = { # example: # 'app_name':'database_name', 'sale': 'sale', 'order': 'order', 'admin': 'default', 'auth': 'default', 'contenttypes': 'default', 'sessions': 'default', } class DBAppsRouter(object): def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None def allow_migrate(self, db, app_label, model=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None ``` 這裡一定要把DATABASE_MAPPING裡面的app名字和app名字對應,不然會讀寫不到,具體可以看上述程式碼,然後在模型類後面給每個模型新增一個app_label: ``` class Meta: app_label = 'order' ``` 最後就是migrate資料庫了,先```makemigrations order```,然後```migrate --database order``` 後面sale ap