如何解决如何在不同的MySQL数据库和不同的Django应用之间进行连接或迁移?
我是Django的新手,非常感谢您的帮助。请让我知道我在犯什么错误。有人可以给我一个至少有2个应用程序和2个数据库的示例。
我的Django项目中有3个应用程序Cherry,Apple和Mango。对于每个应用程序,都有“ models_cherry.py,models_apple.py和models_mango.py”。我已经在MySQL工作台DB1,DB2和DB3中创建了3个数据库。
当我在Windows PowerShell上触发以下查询以进行迁移时,它应在数据库中创建表。迁移应该在数据库上完成。
- python manage.py makemigrations 2)python manage.py migration
以上命令只为一个数据库的一个模型创建表。
我的问题是,我想为所有相应数据库的所有模型创建表。 也就是说,对于数据库数据库DB1中的models_cherry.py文件中的类,对于DB2数据库中的models_apple.py文件中的类以及对于DB3数据库中的models_mango.py文件中的类?
这是settings.py和路由器文件的代码:
#Settings.py
DATABASE_ROUTERS =['apple.Routers.core_router.core_router',#Path to router file
'mango.Routers.man_router.man_router']
DATABASE_APPS_MAPPING = {'core':'core','man':'man'}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql','HOST': 'localhost','PORT': '3306','NAME': 'DB1','USER': 'root','PASSWORD': 'root','OPTIONS': {
'autocommit': True,},'core': {
'ENGINE': 'django.db.backends.mysql','NAME': ' DB2','OPTIONS': {
'autocommit': True,'man': {
'ENGINE': 'django.db.backends.mysql','NAME': ' DB3','OPTIONS': {
'autocommit': True,}
# man_router.py
class man_router:
route_app_labels = {'man'}
def db_for_read(self,model,**hints):
if model._meta.app_label in self.route_app_labels:
return 'man'
return None
def db_for_write(self,**hints):
if model._meta.app_label in self.route_app_labels:
return 'man'
return None
def allow_relation(self,obj1,obj2,**hints):
if (
obj1._meta.app_label in self.route_app_labels or
obj2._meta.app_label in self.route_app_labels
):
return True
return None
def allow_migrate(self,db,app_label,model_name=None,**hints):
if app_label in self.route_app_labels:
return db == 'man'
return None
# core_router.py
class core_router:
route_app_labels = {'core'}
def db_for_read(self,**hints):
if model._meta.app_label in self.route_app_labels:
return 'core'
return None
def db_for_write(self,**hints):
if model._meta.app_label in self.route_app_labels:
return 'core'
return None
def allow_relation(self,**hints):
if app_label in self.route_app_labels:
return db == 'core'
return None
解决方法
在回答您的问题之前的一些问题-
- 为什么要创建3个数据库,而只需要一个。您将需要多个 您的表。
- 您为什么将数据库命名为DBTable1.2 ..?
回答您的问题,因为您在“ settings.py”中提到“数据库”为“ DBTable1”,所以它将仅在“ DBTable1”数据库中创建表。
一个数据库可以有多个表。因此,请相应地命名数据库。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。