django使用多個數據庫的方法實例

通過官方文檔https://docs.djangoproject.com/zh-hans/3.1/topics/db/multi-db/和csdnhttps://blog.csdn.net/songfreeman/article/details/70229839的這兩篇文章可以進行多數據庫的設置。但是設置後可能會出現問題,由於我連接的數據庫是通過inspactdb的方法得到的model。於是在migrate的時候出現瞭問題,會提示 1146, “Table xxx doesn’t exist” 。後來發現問題可能出在路由表上,按照DATABASE_APPS_MAPPING映射之後,django默認的表如果要寫入可能會找不到數據庫。而源代碼裡的映射關系並不包含新加入的app,例如grappelli等。

DATABASE_APPS_MAPPING = {
# example:
# 'app_name':'database_name',
# 'admin': 'default',
# 'users': 'default', #django
'basic_estate': 'basic_estate',
'footstone': 'footstone',
'mall': 'hsmall',
'iot_biz': 'iot_biz',
'mall': 'mall',
'hsuser': 'hsuser',
}

如果要解決這個問題可以修改router代碼,在映射關系內找不到對應的數據庫的情況下返回默認數據庫連接即可:

# -*- coding: utf-8 -*-
"""
@author: obaby
@license: (C) Copyright 2013-2020, obaby@mars.
@contact: [email protected]
@link: http://www.obaby.org.cn
  http://www.h4ck.org.cn
  http://www.findu.co
@file: atabase_router.py.py
@time: 2021/2/26 9:07
@desc:
"""
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 'default'
 
 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 'default'
 
 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

這樣django系統所需的數據庫就能正常創建瞭:

總結

到此這篇關於django使用多個數據庫的文章就介紹到這瞭,更多相關django多數據庫內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: