无法在Django中对多个数据库使用查询集
我可以在默认数据库上使用查询集,但当我尝试在另一个数据库上使用查询集时,就会出现异常。
在我的应用程序中,我使用了两个数据库:sqlite和Mysql。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'abc.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
},
'second' : {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'abc', # Or path to database file if using sqlite3.
'USER': 'abcdb', # Not used with sqlite3.
'PASSWORD': 'xxxxx', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
当我在第一个数据库上使用查询集时,没有出现任何异常。但是在使用第二个数据库时,却出现了“表不存在”的错误。
TemplateSyntaxError at /abc/xyz/
Caught DatabaseError while rendering: no such table: second.tablename
Request Method: GET
Request URL: http://127.0.0.1:8000/xxx/yyyy/?q=abcd
Django Version: 1.3.1
Exception Type: TemplateSyntaxError
Exception Value:
Caught DatabaseError while rendering: no such table: second.tablename
2 个回答
0
在Django中使用多个数据库的最佳方法是通过路由来管理这些数据库。这里有相关的文档:
https://docs.djangoproject.com/en/1.11/topics/db/multi-db/#topics-db-multi-db-routing
下面是文档中的一个完整示例:
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
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in the auth app is involved.
"""
if obj1._meta.app_label == 'auth' or \
obj2._meta.app_label == 'auth':
return True
return None
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if app_label == 'auth':
return db == 'auth_db'
return None
如果在查询时没有指定数据库,Django会根据表的名称自动选择正确的数据库。
希望这对你有帮助 :)
1
谢谢你的回复,汤姆,
我手动尝试了第二个数据库,结果对我有效。
$model_seconddb.modelname.objects.using('seconddatabasename').filter(name='xxx')
当两个数据库里并不是所有的表都存在时,可以使用这个方法。
如果你想使用默认数据库,就不需要写(using)这个词。它会直接从默认数据库中查询数据。