我正在嘗試創建一個應用程式,其中一臺服務器與許多其他作業服務器進行通信。這些服務器每個都有自己的資料庫,該資料庫應該只包含他們自己模型的表。我創建了一個資料庫路由器,不幸的是它不起作用,因為 migrate 命令繼續在資料庫中創建 auth、contenttypes 和幾乎所有 Django 應用程式模型,根據路由器,應該不包含這些,只包含作業服務器特定的模型。
預期在資料庫中:
- 作業服務器模型 1
實際在資料庫中產生:
- 作業服務器模型 1
- auth_group
- auth_group_permissions
- auth_permission
- auth_user
- auth_user_groups
- 所有其余的 django 模型
設定中的代碼:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'server_1_db',
'USER': 'postgres',
'PASSWORD': 'admin',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
DATABASE_ROUTERS = ['ApplicationServer_2.db_routers.RestRouter']
路由器代碼:
class RestRouter:
app_labels = {"DoNOTadd", "auth", "admin", "sessions", "contenttypes"}
def db_for_read(self, model, **hints):
if model._meta.app_label not in self.app_labels:
return 'default'
return "For read db"
def db_for_write(self, model, **hints):
if model._meta.app_label not in self.app_labels:
return "default"
return "For write db"
def allow_relation(self, obj1, obj2, **hints):
if (
obj1._meta.app_label not in self.app_labels or
obj2._meta.app_label not in self.app_labels
):
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label not in self.app_labels:
print(app_label)
return db == "default"
return None
我做錯了什么?在allow migrate中,僅列印了預期的 app_label,這意味著不應遷移 auth、admin 等,但它們仍然被遷移了嗎?
uj5u.com熱心網友回復:
您allow_migrate應該回傳以指示不允許在此資料庫中遷移的False應用程式以外的應用程式:app_labels
def allow_migrate(self, db, app_label, model_name=None, **hints):
if app_label not in self.app_labels:
return db == "default"
return False
像你一樣回傳None意味著這個路由器不關心這個遷移。從檔案中allow_migrate:
確定是否允許在別名為 db 的資料庫上運行遷移操作。如果操作應該運行,則回傳 True,如果不應該運行,則回傳 False,如果路由器沒有意見,則回傳 None。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/478058.html
標籤:Python django 数据库 django模型 django 数据库
