简体   繁体   English

光标如何在Django中选择数据库

[英]How cursor selects a database in django

I have a question for cursor in python, if I have more than one database in my settings and I want to open a cursor in a function that will export data to excel file with openpyxl. 我在python中有一个游标问题,如果我的设置中有多个数据库,并且想在一个函数中打开游标,该函数将使用openpyxl将数据导出到excel文件。 My question is how my cursor will know which database to connect and how this does it. 我的问题是我的光标将如何知道要连接的数据库以及它是如何做到的。

Thanks in advance 提前致谢

DATABASES  = {
'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'default',
    'USER': 'postgres',
    'PASSWORD': 'xxxx',
    'HOST': '127.0.0.1',
    'PORT': '5432',
},
'test1': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'test1',
    'USER': 'postgres',
    'PASSWORD': 'xxxx',
    'HOST': '127.0.0.1',
    'PORT': '5433',
},
'test2': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'test2',
    'USER': 'postgres',
    'PASSWORD': 'xxxx',
    'HOST': '127.0.0.1',
    'PORT': '5432',
}
}

It will use the default database. 它将使用default数据库。 If you need to use a different database use: 如果您需要使用其他数据库,请使用:

from django.db import connections
cursor = connections['my_db_alias'].cursor()

From the docs here . 这里的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM