我在 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 实例上吗?
最佳答案
我重写了路由类,如下所述:
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
关于mysql - 在django中使用多个数据库并获取表不存在错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284722/