django多数据库的实现

本文详细介绍了如何在新Django项目中通过设置DATABASES和DATABASE_ROUTERS实现按应用(app)分离数据库,包括配置文件修改、自定义路由类(dbrouter.py)以及在settings.py中的整合步骤。重点解决读关联数据时的注意事项,确保项目高效稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文档:

 

 * https://docs.djangoproject.com/en/1.2/topics/db/multi-db/#topics-db-multi-db-routing

 * http://blog.sina.com.cn/s/blog_3fbe78a60100p68a.html

 

目的:新项目中实现 按app实现数据库的分离

 

以非IC模块product为例

 

1. setting.py中加入

...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'xiaofei_ecgoo',                      # Or path to database file if using sqlite3.
        'USER': 'xiaofei',                      # Not used with sqlite3.
        'PASSWORD': '*****',                  # Not used with sqlite3.
        'HOST': '192.168.0.8',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },
     'product': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'xiaofei_product',                      # Or path to database file if using sqlite3.
        'USER': 'xiaofei',                      # Not used with sqlite3.
        'PASSWORD': '*******',                  # Not used with sqlite3.
        'HOST': '192.168.0.8',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
 }
...

 

2.增加dbrouter.py

class MyAppRouter(object):
    """A router to control all database operations on models in
    the myapp application"""

    def db_for_read(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'product':
            return 'product'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'product':
            return 'product'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in myapp is involved"
        if obj1._meta.app_label == 'product' or obj2._meta.app_label == 'product':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the myapp app only appears on the 'other' db"
        if db == 'product':
            return model._meta.app_label == 'product'
        elif model._meta.app_label == 'product':
            return False
        return None

class MasterSlaveRouter(object):
    """A router that sets up a simple master/slave configuration"""

    def db_for_read(self, model, **hints):
        "Point all read operations to a random slave"
        return 'default'

    def db_for_write(self, model, **hints):
        "Point all write operations to the master"
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation between two objects in the db pool"
        db_list = ('default','product')
        if obj1._state.db in db_list and obj2._state.db in db_list:
            return True
        return None

    def allow_syncdb(self, db, model):
        "Explicitly put all models on all databases."
        return True

 

3.配置settings.py

DATABASE_ROUTERS = ['new_ecgoo.dbrouter.MyAppRouter', 'new_ecgoo.dbrouter.MasterSlaveRouter']

 

 

注意:

写道
刚调试时,有几个页面一直报错,后发现数据库分离后,在读关联数据时,有几个写法要注意:
如:
ic = Ic.objects.filter(u__username=name)
应改为:
user = User.objects.get(username = name)
ic = Ic.objects.filter(u=user)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值