我以我个人的Mynote工程说明,目的是要在backend这个app里面设置不同的model对应daysn和bear两个数据库进行操作
现在我们先简单对一个完全新建的django工程配置一个自动在mysql生成表的这么一个东西,
配置setting
然后随便写个model
然后
E:大数据DjangoMyNoteMynote>python manage.py makemigrations backend Migrations for 'backend': backendmigrations 001_initial.py - Create model test E:大数据DjangoMyNoteMynote>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, backend, contenttypes, sessions Running migrations: Applying backend.0001_initial... OK
然后就创建了一个表,好,这是前提。ps,其他表先建了
好,从这里开始记录一个完整的一个app对应多个数据库的过程,综合了n篇博客妈的没有一篇靠谱
首先我们建立一个空的app,假设叫another
那么我们在我们的主工程的setting肯定要注册进去,顺便配置一下我们的数据库连接
DATABASES = { #系统默认加载的数据库daysn,于是这里的数据库连接名为default 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'daysn', 'USER':'root', "PASSWORD":'123456', "HOST":"*.*.*.*", "PORT":"3306", "CONN_MAX_AGE":7*3600, },
#系统加载的数据库第二个bear,于是这里的数据库连接名为default
'default2': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'bear', 'USER':'root', "PASSWORD":'123456', "HOST":"*。*。*。*", "PORT":"3306", "CONN_MAX_AGE":7*3600, }, }
#待会我们在主工程的目录下新建一个DatabaseAppRouter文件,里面定义了一个DatabaseAppsRouter的class
DATABASE_ROUTERS = ['Mynote.DatabaseAppRouter.DatabaseAppsRouter']
#两个应用对应不同的数据库 DATABASE_APPS_MAPPING = { 'backend': 'default', 'another': 'default2', }
好,现在我们新建一个路由就像上面说的
然后下面这段代码完全copy
# -*- coding: utf-8 -*- from django.conf import settings DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING class DatabaseAppsRouter(object): """ A router to control all database operations on models for different databases. In case an app is not set in settings.DATABASE_APPS_MAPPING, the router will fallback to the `default` database. Settings example: DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'} """ def db_for_read(self, model, **hints): """"Point all read operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **hints): """Point all write operations to the specific database.""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **hints): """Allow any relation between apps that use the same database.""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False return None # for Django 1.4 - Django 1.6 def allow_syncdb(self, db, model): """Make sure that apps only appear in the related database.""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None # Django 1.7 - Django 1.11 def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure that apps only appear in the related database. 根据app_label的值只在相应的数据库中创建一个表,如果删除该def或 不指定过滤条件,则一个Model会在每个数据库里都创建一个表。 """ if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None
然后我们可以去写我们的类了,因为我们的目的是要在backend这个app里面设置不同的model同时对应daysn和bear这两个数据库
那么测试如下,在backend的model.py里面加入这些玩意儿
from django.db import models # Create your models here. class test(models.Model): test_id = models.IntegerField() test_a_id = models.IntegerField() class mt(models.Model): test_id = models.IntegerField() test_a_id = models.IntegerField() class another(models.Model): test_id = models.IntegerField() test_a_id = models.IntegerField() class Meta: app_label = 'another' class dsasdas(models.Model): test_id = models.IntegerField() test_a_id = models.IntegerField() class Meta: app_label = 'another'
同步数据库要使用的是
python manage.py makemigrations
然后同步default
python manage.py migrate
同步非default
python manage.py migrate --database==default2
这样才会同步完两个数据库
好的,一个app连接多个数据库表演完毕。
ps:我认为应该有其他方式啊。。不应该要通过新建一个没怎么用的空app another来搞,哪路大神知道的话希望能救下小弟。