与Django相同的数据库不同的数据库 [英] Different databases with the same models on Django
问题描述
我有以下问题:
对于每个用户(或一组用户),我需要一个具有相同型号的不同数据库。我有一种方法来找出与用户相关的数据库。问题是我每次查询时都必须使用方法。
I need a different database with the same models for each user (or set of users). I have a way of finding out to which database the user is related. The issue is I always have to use the using
method on every query I make.
例如:
Thing.objects.using('appropriate_database').all()
有没有办法避免使用使用
并使用户/数据库关系隐含? p>
Is there a way to avoid the use of using
and making the user/database relationship implicit somehow?
推荐答案
我们做到了!让我解释一下。
We did it! Let me explain how.
我们写了一个自定义中间件,并将其注册为我们的settings.py文件中的中间件类。
We wrote a custom middleware and registered it as an middleware class inside our settings.py file.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'our.custom.middleware.Class',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
这个中间件有一个 process_request 方法创建一个线程变量(从线程导入本地
)来存储当前用户的相应数据库名称。由于每个请求都由不同的线程处理,我们知道我们的变量的值不会被另一个线程意外地更改。
This middleware has a process_request method that creates a thread variable (from threading import local
) to store the appropriate database name for the current user. Since every request is handled by a different thread, we know that our variable's value won't be accidently changed by another thread.
下一步是创建一个数据库路由器,并将其注册为
The next step was creating a Database Router and registering it as such.
DATABASE_ROUTERS = ('our.custom.database.Router',)
注意:默认的 settings.py
没有一个 DATABASE_ROUTERS
变量。您必须创建它。
Attention: The default settings.py
doesn't have a DATABASE_ROUTERS
variable. You'll have to create it.
我们的自定义路由器
与 db_for_read
和 db_for_write
。这些方法唯一的办法是返回存储在我们的线程变量上的数据库名。
Our custom Router
has the same implementations for db_for_read
and db_for_write
. The only thing these methods do is return the database name stored on our thread variable.
就是这样。现在,每次需要恢复或保存模型对象时,我们不必使用调用。
That's it. Now we don't have to call using
every time we need to recover or save model objects.
这篇关于与Django相同的数据库不同的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!