django使用多数据库,以及admin管理使用的方法。

来源:互联网 发布:arr slice js 编辑:程序博客网 时间:2024/05/22 08:12

django中可以从多个数据库中读写数据。

由于业务需要,开发中遇到了需要读写另一个数据库的情况。

以下是工作时的遇到问题的解决方法:


django多数据库的配置:

1. 在数据库配置字段,增加需要连接的数据库

在settings.py文件下找到

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'ire_test',        'USER': 'root',        'PASSWORD': '123456',        'HOST': '127.0.0.1',        'PORT': '3306',    },    'genius': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'ire_my',        'USER': 'root',        'PASSWORD': '123456',        "HOST": "127.0.0.1",        'PORT': '3306',    },}


2. 编写需要调用这个数据库的model

在models.py文件下找到

@python_2_unicode_compatibleclass StockCode(models.Model):    com_code = models.IntegerField('公司代码', null=True, db_column='COMCODE')    stock_code = models.CharField('股票代码', max_length=12, null=True, db_column='STOCKCODE')    def __str__(self):        return "{self.com_code} {self.stock_code}".format(self=self)    @staticmethod    def get_com_code(stock_code):        sc = StockCode.objects.filter(stock_code=stock_code).first()        if sc:            return sc.com_code        else:            return None    class Meta:        # app_label = 'convertfirst'        db_table = 'stk_code'        verbose_name = '公司信息'        verbose_name_plural = '公司信息'        managed = False

首先需要给model的字段设置好映射的数据库字段db_column,并在meta中设置好连接的db_table,managed=False为同步数据库时不同步这个model

这里需要注意的是,model中的字段可以只设置需要的字段,而不需要数据库中所有字段。


3.编写数据库路由

由于使用了多个数据库,所以我们需要编写一个数据库路由来告诉django需要对哪些model进行orm时对于那个数据库。

新建一个db_router.py文件,编写一个转发器

# coding=utf-8from __future__ import (unicode_literals, absolute_import)genius_models = (    'ConvertFirst',    'StockCode',)class ConvertFirstRouter(object):    """    A router to control all database operations on models in the    watchlist application.    """    def db_for_read(self, model, **hints):        """        Attempts to read watchlist models go to genius DB.        """        if model.__name__ in genius_models:            return 'genius'         return None    def db_for_write(self, model, **hints):        """        Attempts to write watchlist models go to genius DB.        """        if model.__name__ in genius_models:            return 'genius'         return None    def allow_relation(self, obj1, obj2, **hints):        """        Allow relations if a model in the watchlist app is involved.        """        if obj1.__class__.__name__ in genius_models or obj2.__class__.__name__ in genius_models:            return True        return None    def allow_migrate(self, db, model):        """        Make sure the watchlist app only appears in the watchlist database.        """        if db in genius_models:            return model._meta.app_label in genius_models        elif model._meta.app_label in genius_models:            return False

其中genius_model元组中的classname为需要特殊处理的model类,可自行定义(这里主要是需要特殊处理的model与不需要特殊处理的model存在一个app的models.py文件下,所以这里不能使用app_label来区分,具体方法有很多)。

通过上述文件中的方法可以告诉django在处理这些model的orm关系时,使用settings里那个数据库进行连接。


4. admin里的运用

admin里的运用就和再次modeladmin一样了。

0 0
原创粉丝点击