我正在使用數據庫路由器,因此我有兩個數據庫用於我的應用程序。一個數據庫用於默認的django數據,另一個用於數據庫。無法使用數據庫路由器save_model保存
在我的管理員,我已經覆蓋save_model
函數爲了保存created_by
變量,但我無法做到這一點。
Cannot assign "<User: testuser>": the current database router prevents this relation.
數據庫路由器:
from django.conf import settings
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
"""Point all read operations to the specific database."""
if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
return settings.DATABASE_APPS_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
if settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
return settings.DATABASE_APPS_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 = settings.DATABASE_APPS_MAPPING.get(obj1._meta.app_label)
db_obj2 = settings.DATABASE_APPS_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 model._meta.app_label in ['south']:
return True;
elif db in settings.DATABASE_APPS_MAPPING.values():
return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) == db
elif settings.DATABASE_APPS_MAPPING.has_key(model._meta.app_label):
return False
return None
管理:
class SomeEntityAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
user = request.user._wrapped if hasattr(request.user,'_wrapped') else request.user
if not obj.created_by:
obj.created_by = user
obj.save()
我甚至嘗試用save(using='thedb')
定義不同的數據庫,但不工作的。我的數據庫路由器錯了嗎?
這一切都有道理。所以我顯然沒有別的選擇,只能回到一個數據庫。 – JavaCake 2014-10-27 07:40:17
優秀評論。我發現有關這些問題的信息太少。但我不想倒退。 @JavaCake,之後你有幸運嗎? – 2016-10-13 21:12:33