Django:动态数据库文件

Con*_*ius 15 django django-models django-database

在我的Django项目中,我依赖于第三方应用程序,该应用程序使用已知模式在各种目录中生成SQLite缓存文件.

我想使用Django模型访问这些数据库,但显然我不能使用静态DATABASES设置.

如何在任意路径上动态打开SQLite数据库?

编辑

正如Byron Ruth指出的那样,解决方案是将它django.db.connectionsusingQuerySet中的函数结合使用.

Byr*_*uth 30

django.db.connections是一个DATABASES在您的设置中定义的简单包装器.包装类在这里: django.db.utils#L137-L227

from django.db import connections

# Add connection information dynamically..
connections.databases['new-alias'] = { ... }
# Ensure the remaining default connection information is defined.
# EDIT: this is actually performed for you in the wrapper class __getitem__
# method.. although it may be good to do it when being initially setup to
# prevent runtime errors later.
# connections.databases.ensure_defaults('new-alias')

# Use the new connection
conn = connections['new-alias']
Run Code Online (Sandbox Code Playgroud)

  • @monkut它们将在整个过程中存储.一个快速的`if'new-alias'不在connections.databases`中检查将确保设置始终存在.另外,如果您_really_想要临时数据库连接,请尝试以下操作:https://gist.github.com/bruth/7467130 (2认同)