天天看點

在django中使用多個資料庫

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 來指定同步哪一個, 如下:

[plain]  view plain  copy

  1. <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  
  2. $ ./manage.py syncdb --database=users</tt>  

那麼程式中如何來選擇呢?

比如,下面的代碼将選擇default資料庫

[python]  view plain  copy

  1. <span style="font-family:monospace;color:#234f32;">>>> # This will run on the 'default' database.  
  2. >>> Author.objects.all()  
  3. >>> # So will this.  
  4. >>> Author.objects.using('default').all()</span>  

但是下面的代碼将選擇other資料庫

[python]  view plain  copy

  1. <span style="font-family:monospace;color:#234f32;">>>> # This will run on the 'other' database.  
  2. >>> Author.objects.using('other').all()</span>  

上面是查詢的情況,儲存的使用也一樣,也是通過using來指定,如下:

[python]  view plain  copy

  1. <span style="font-family:monospace;color:#234f32;">>>> my_object.save(using='legacy_users')</span>  

删除的時候

[python]  view plain  copy

  1. <span style="font-family:monospace;color:#234f32;">>>> u = User.objects.using('legacy_users').get(username='fred')  
  2. >>> u.delete() # will delete from the `legacy_users` database</span>