django使用多个数据库的方法实例
通过官方文档https://docs.djangoproject.com/zh-hans/3.1/topics/db/multi-db/和csdnhttps://blog.csdn.net/songfreeman/article/details/70229839的这两篇文章可以进行多数据库的设置。但是设置后可能会出现问题,由于我连接的数据库是通过inspactdb的方法得到的model。于是在migrate的时候出现了问题,会提示1146,“Tablexxxdoesn'texist”。后来发现问题可能出在路由表上,按照DATABASE_APPS_MAPPING映射之后,django默认的表如果要写入可能会找不到数据库。而源代码里的映射关系并不包含新加入的app,例如grappelli等。
DATABASE_APPS_MAPPING={ #example: #'app_name':'database_name', #'admin':'default', #'users':'default',#django 'basic_estate':'basic_estate', 'footstone':'footstone', 'mall':'hsmall', 'iot_biz':'iot_biz', 'mall':'mall', 'hsuser':'hsuser', }
如果要解决这个问题可以修改router代码,在映射关系内找不到对应的数据库的情况下返回默认数据库连接即可:
#-*-coding:utf-8-*- """ @author:obaby @license:(C)Copyright2013-2020,obaby@mars. @contact:root@obaby.org.cn @link:http://www.obaby.org.cn http://www.h4ck.org.cn http://www.findu.co @file:atabase_router.py.py @time:2021/2/269:07 @desc: """ fromdjango.confimportsettings DATABASE_MAPPING=settings.DATABASE_APPS_MAPPING classDatabaseAppsRouter(object): """ Aroutertocontrolalldatabaseoperationsonmodelsfordifferent databases. Incaseanappisnotsetinsettings.DATABASE_APPS_MAPPING,therouter willfallbacktothe`default`database. Settingsexample: DATABASE_APPS_MAPPING={'app1':'db1','app2':'db2'} """ defdb_for_read(self,model,**hints): """"Pointallreadoperationstothespecificdatabase.""" ifmodel._meta.app_labelinDATABASE_MAPPING: returnDATABASE_MAPPING[model._meta.app_label] return'default' defdb_for_write(self,model,**hints): """Pointallwriteoperationstothespecificdatabase.""" ifmodel._meta.app_labelinDATABASE_MAPPING: returnDATABASE_MAPPING[model._meta.app_label] return'default' defallow_relation(self,obj1,obj2,**hints): """Allowanyrelationbetweenappsthatusethesamedatabase.""" db_obj1=DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2=DATABASE_MAPPING.get(obj2._meta.app_label) ifdb_obj1anddb_obj2: ifdb_obj1==db_obj2: returnTrue else: returnFalse returnNone defallow_syncdb(self,db,model): """Makesurethatappsonlyappearintherelateddatabase.""" ifdbinDATABASE_MAPPING.values(): returnDATABASE_MAPPING.get(model._meta.app_label)==db elifmodel._meta.app_labelinDATABASE_MAPPING: returnFalse returnNone defallow_migrate(self,db,app_label,model=None,**hints): """ Makesuretheauthapponlyappearsinthe'auth_db' database. """ ifdbinDATABASE_MAPPING.values(): returnDATABASE_MAPPING.get(app_label)==db elifapp_labelinDATABASE_MAPPING: returnFalse returnNone
这样django系统所需的数据库就能正常创建了:
总结
到此这篇关于django使用多个数据库的文章就介绍到这了,更多相关django多数据库内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。