django操作多資料庫
1、 新增資料庫路由分配檔案
在專案資料夾裡建立‘database_router’檔案。將下面的程式碼複製到該檔案裡。
from django.conf import settings DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING class DatabaseAppsRouter(object): """ A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {`app1`: `db1`, `app2`: `db2`} """ 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
2、在settings.py檔案中配置多資料庫
# Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { `default`: { `ENGINE`: `django.db.backends.mysql`, `NAME`: `django_test`, `HOST`: `127.0.0.1`, `USER`: `root`, `PASSWORD`: `123456`, `PORT`: `3306`, }, #配置第二個資料庫 `test`: { `ENGINE`: `django.db.backends.mysql`, `NAME`: `xsanjiaocheng`, `HOST`: `127.0.0.1`, `USER`: `root`, `PASSWORD`: `123456`, `PORT`: `3306`, } }
#設定資料庫路由,將django_test改為你專案的名稱。
DATABASE_ROUTERS = [`django_test.database_router.DatabaseAppsRouter`]
#配置資料庫與app的對應關係
DATABASE_APPS_MAPPING = { # example: # `app_name`:`database_name`, # `app01`: `test`, `app01`: `default`, `app02`: `test`, }
3、 在對應的app裡的models.py檔案里正常建立資料表即可(在建立表時儘量不要使用同樣的表名)
app01中的models.py:
class django_test_1(models.Model): abc = models.CharField(max_length=20) class Meta: app_label=`app01` app02中的models.py: class test_1(models.Model): tests= models.CharField(max_length=20)
4、 生成遷移檔案
和以前一樣:python manage.py makemigrations
5、 遷移資料庫
遷移時需指定資料庫名
python manage.py migrate database=test
如果針對已建立好的資料庫建立對應的models.py檔案不用生成遷移檔案,直接執行“python manage.py inspectdb > app02/models.py –database=test”的命令即可。
在django 2.1.1版本中需要執行“python manage.py inspectdb –database=test > app02/models.py ”
6、運算元據庫
1)手動選擇資料庫
django_test_1.objects.using(`default`).create(abc=`hdajh`)
2)自動選擇資料庫
和以前一樣不加using()。
7、 配置urls.py
匯入對應app的views.py的檔案。最好命名個別名,或者給views.py檔案重新命名。
其他使用和以前一樣。