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. 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. If you need to use a different database use:
from django.db import connections
cursor = connections['my_db_alias'].cursor()
From the docs here.