django 多数据库应用

http://www.it165.net/pro/html/201501/32074.html

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

django实现多数据库应用

 (2011-02-11 16:09:41)
标签: 

it

分类: django

增加应用:

python ./manage.py startapp stock

python ./manage.py startapp weather

 

stock下models.py, admin.py:

#-*- coding: utf-8 -*-

from django.db import models

# Create your models here.

class admintest2(models.Model):
    name = models.CharField('姓名', max_length=6, unique=True)
    gender = models.CharField('性别', choices=(('M', '男'), ('F', '女')), max_length=1)
    telphone = models.CharField('电话', max_length=20)
    mobile = models.CharField('手机', max_length=11, blank=True)

    def __unicode__(self):
        return self.name

 

#-*- coding: utf-8 -*-

from moss.stock.models import admintest2
from django.contrib import admin
 
class Admintest2Admin(admin.ModelAdmin):
    list_display = ('name', 'gender', 'telphone', 'mobile', )
    search_fields = ('name', 'gender', 'telphone', 'mobile', )
    #list_filter = ('name', 'gender', 'telphone', 'mobile', )
    ordering = ('name', )
    #fields = ('name', 'telphone', 'mobile', )
    #filter_horizontal = ('name', )
    fieldsets = [(None, {'fields': ['name', 'gender']}),
                 ('联系方式', {'fields': ['telphone', 'mobile']}),
                ]
   
admin.site.register(admintest2, Admintest2Admin)

 

weather下models.py, admin.py:

#-*- coding: utf-8 -*-

from django.db import models

# Create your models here.

class admintest3(models.Model):
    name = models.CharField('姓名', max_length=6, unique=True)
    gender = models.CharField('性别', choices=(('M', '男'), ('F', '女')), max_length=1)
    telphone = models.CharField('电话', max_length=20)
    mobile = models.CharField('手机', max_length=11, blank=True)

    def __unicode__(self):
        return self.name

 

#-*- coding: utf-8 -*-

from moss.weather.models import admintest3
from django.contrib import admin
 
class Admintest3Admin(admin.ModelAdmin):
    list_display = ('name', 'gender', 'telphone', 'mobile', )
    search_fields = ('name', 'gender', 'telphone', 'mobile', )
    #list_filter = ('name', 'gender', 'telphone', 'mobile', )
    ordering = ('name', )
    #fields = ('name', 'telphone', 'mobile', )
    #filter_horizontal = ('name', )
    fieldsets = [(None, {'fields': ['name', 'gender']}),
                 ('联系方式', {'fields': ['telphone', 'mobile']}),
                ]
   
admin.site.register(admintest3, Admintest3Admin)

 

配置setting.py:

INSTALLED_APPS = (
    ....    
    'moss.stb',
    'moss.stock',
    'moss.weather',
)

 

需求:

权限管理(默认)使用pms数据库

stb使用bss数据库

stock使用stock数据库

weather使用weather数据库

 

目标:

统一权限管理,但每个应用有自己独立的数据库(不限制在一个服务器上)。

 

django实现:

配置setting.py:

DATABASES = {
    'default': {
        'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_pms',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },

    'stb': {
        'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_bss',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },
       
    'stock': {
        'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_stock',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },
   
    'weather': {
        'ENGINE': 'mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'django_weather',                      # Or path to database file if using sqlite3.
        'USER': 'root',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': 'localhost',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    },
   
}

 

增加dbrouter.py:

#-*- coding: utf-8 -*-

class MossDBRouter(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'"
        return self.__app_router(model)

    def db_for_write(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        return self.__app_router(model)

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

    def allow_syncdb(self, db, model):
        #print "model._meta.app_label = %s, db = %s", (model._meta.app_label, db)
        
        "Make sure the myapp app only appears on the 'other' db"
        return self.__app_router(model) == db
   
    def __app_router(self, model):
        if model._meta.app_label == 'stb':
            return 'stb'
        elif model._meta.app_label == 'stock':
            return 'stock'
        elif model._meta.app_label == 'weather':
            return 'weather'
        else:
            return 'default'

 

配置setting.py:

DATABASE_ROUTERS = ['moss.dbrouter.MossDBRouter']

 

同步数据库:

python ./manage.py syncdb

python ./manage.py syncdb --database=stb

python ./manage.py syncdb --database=stock

python ./manage.py syncdb --database=weather

 

启动应用:

python ./manage.py runserver 8000

登录:http://localhost:8000/admin,确认。

 

参考链接:

http://docs.djangoproject.com/en/1.2/topics/db/multi-db/


分享到: 微信 更多