转载自: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/