我在django中有以下数据库设置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'default_db',
},
'otherdb': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'other_db',
}
}
默认模型是:
class Notification(models.Model):
otherdb模型是:
class Entity(models.Model):
在我的视图代码中,我只是这样做:
entities = Entity.objects.get(pk=pk)
for entity in entities:
print entity
根据django文档,django将为您进行数据库路由。我有两个数据库的模型。当我运行这个时,我得到一个错误:
1146, "Table 'default_db.Entity' doesn't exist"
它应该寻找other_db.Entity
我需要做些什么才能在我的ec2实例上进行路由?
答案 0 :(得分:0)
我覆盖了这里提到的路由类:
https://docs.djangoproject.com/en/dev/topics/db/multi-db/#topics-db-multi-db-hints
我使用了以下功能:
class AuthRouter(object):
"""
A router to control all database operations on models in the
auth application.
"""
def db_for_read(self, model, **hints):
"""
Attempts to read auth models go to auth_db.
"""
if model._meta.app_label == 'auth':
return 'auth_db'
return None
def db_for_write(self, model, **hints):
"""
Attempts to write auth models go to auth_db.
"""
if model._meta.app_label == 'auth':
return 'auth_db'
return None