轉載自:http://blog.csdn.net/feng88724/article/details/7177957
1.2之後, django支持在項目中使用多個DB. 那麼到底如何使用呢?
1. 修改 settings.py
01
DATABASES
=
{
02
'default'
:
{
03
'NAME'
:
'app_data'
,
04
'ENGINE'
:
'django.db.backends.postgresql_psycopg2'
,
05
'USER'
:
'postgres_user'
,
06
'PASSWORD'
:
's3krit'
07
},
08
'users'
:
{
09
'NAME'
:
'user_data'
,
10
'ENGINE'
:
'django.db.backends.mysql'
,
11
'USER'
:
'mysql_user'
,
12
'PASSWORD'
:
'priv4te'
13
}
14
}
15
16
DATABASE_ROUTERS
=
[
'path.to.MyAppRouter'
]
2. 實現自己的DB routers,這裏決定了每個程序使用的是哪個DB。
01
class
MyAppRouter(
object
):
02
"""A
router to control all database operations on models in
03
the
myapp application"""
04
05
def
db_for_read(
self
,
model,
*
*
hints):
06
"Point
all operations on myapp models to 'other'"
07
if
model._meta.app_label
=
=
'myapp'
:
08
return
'other'
09
return
None
10
11
def
db_for_write(
self
,
model,
*
*
hints):
12
"Point
all operations on myapp models to 'other'"
13
if
model._meta.app_label
=
=
'myapp'
:
14
return
'other'
15
return
None
16
17
def
allow_relation(
self
,
obj1, obj2,
*
*
hints):
18
"Allow
any relation if a model in myapp is involved"
19
if
obj1._meta.app_label
=
=
'myapp'
or
obj2._meta.app_label
=
=
'myapp'
:
20
return
True
21
return
None
22
23
def
allow_syncdb(
self
,
db, model):
24
"Make
sure the myapp app only appears on the 'other' db"
25
if
db
=
=
'other'
:
26
return
model._meta.app_label
=
=
'myapp'
27
elif
model._meta.app_label
=
=
'myapp'
:
28
return
False
29
return
None
同步數據庫的時候,默認會同步到Default數據庫,當然也可以通過 --database 來指定同步哪一個, 如下:
- <tt class="xref std std-djadminopt docutils literal" style="text-decoration: none; white-space: nowrap; color: rgb(35, 79, 50); margin-left: 0px; margin-right: 0px; border-bottom-width: 1px; border-bottom-color: rgb(35, 79, 50); border-bottom-style: dotted; ">$ ./manage.py syncdb
- $ ./manage.py syncdb --database=users</tt>
那麼程序中如何來選擇呢?
比如,下面的代碼將選擇default數據庫
- <span style="font-family:monospace;color:#234f32;">>>> # This will run on the 'default' database.
- >>> Author.objects.all()
- >>> # So will this.
- >>> Author.objects.using('default').all()</span>
但是下面的代碼將選擇other數據庫
- <span style="font-family:monospace;color:#234f32;">>>> # This will run on the 'other' database.
- >>> Author.objects.using('other').all()</span>
上面是查詢的情況,保存的使用也一樣,也是通過using來指定,如下:
- <span style="font-family:monospace;color:#234f32;">>>> my_object.save(using='legacy_users')</span>
刪除的時候
- <span style="font-family:monospace;color:#234f32;">>>> u = User.objects.using('legacy_users').get(username='fred')
- >>> u.delete() # will delete from the `legacy_users` database</span>
更多內容請至此查看: https://docs.djangoproject.com/en/1.3/topics/db/multi-db/