在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 来指定同步哪一个, 如下:

$ ./manage.py syncdb
$ ./manage.py syncdb --database=users

那么程序中如何来选择呢?

比如,下面的代码将选择default数据库

>>> # This will run on the 'default' database.
>>> Author.objects.all()

>>> # So will this.
>>> Author.objects.using('default').all()

但是下面的代码将选择other数据库

>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()

上面是查询的情况,保存的使用也一样,也是通过using来指定,如下:

>>> my_object.save(using='legacy_users')

删除的时候

>>> u = User.objects.using('legacy_users').get(username='fred')
>>> u.delete() # will delete from the `legacy_users` database

更多内容请至此查看: https://docs.djangoproject.com/en/1.3/topics/db/multi-db/


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值