Django:动态数据库文件 [英] Django: dynamic database file
问题描述
在我的Django项目中,我有一个第三方应用程序的依赖,该应用程序在具有已知架构的各种目录中生成SQLite缓存文件。
In my Django project I have a dependency for a third party application that produces SQLite cache files in various directories with a known schema.
我想使用Django模型访问这些数据库,但显然我不能使用静态的 DATABASES
安装。
I'd like to use Django models to access those databases, but obviously I cannot use a static DATABASES
setup.
如何在任意路径上动态打开SQLite数据库?
How can I dynamically open a SQLite database on an arbitrary path?
编辑
正如Byron Ruth指出的那样,解决方案是将 django.db.connections
与 在QuerySet中使用
函数。
As Byron Ruth pointed out, the solution is to use the django.db.connections
in conjunction with the using
function in the QuerySet.
推荐答案
django.db.connections
是在您的设置中定义的 DATABASES
之间的简单包装。包装类在这里:
django.db.utils# L137-L227
The django.db.connections
is a simple wrapper around DATABASES
defined in your settings. The wrapper class is here:
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']
这篇关于Django:动态数据库文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!