Django unable to get values from database in another table

时间:2019-04-08 13:47:13

标签: python mysql django

I need to join tables in django. I am using cursor object to get all values from database.

settings.py

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'integration',
       'USER': '****',
       'PASSWORD': '***',
       'HOST': '***',
       'PORT': '3306',   #my port is 3306
   },
   'configuration': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'configuration',
       'USER': '****',
       'PASSWORD': '****',
       'HOST': '****',
       'PORT': '3306',   #my port is 3306
   }
}

views.py

from django.db import connection
def opdb(request):
   with connection['configuration'].cursor() as cursor:
       cursor = connection.cursor()
       cursor.execute("SELECT * from integrations")
       row = cursor.fetchone()
       print(row)

Models.py

class Integrations(models.Model):
    trail_userid = models.IntegerField()
    trail_username = models.CharField(max_length=255)
    client_tool_id = models.CharField(max_length=50)
    automation_tool_id = models.CharField(max_length=255)
    Project = models.CharField(max_length=255)
    environment = models.CharField(max_length=255, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    endpoint = models.TextField()
    username = models.CharField(max_length=255, blank=True, null=True)
    password = models.CharField(max_length=255, blank=True, null=True)
    auth_token = models.CharField(max_length=255, blank=True, null=True)
    connectivity_status = models.CharField(max_length=255)
    subscription_status = models.CharField(max_length=255)

    class Meta:
        managed = False
        db_table = 'integrations'

integrations is a table in configuration database. Unable to get all values in integrations. ERROR: with connection['configuration'].cursor() as cursor: TypeError: 'DefaultConnectionProxy' object is not subscriptable

1 个答案:

答案 0 :(得分:0)

You are using a different database "configuration".You should use below code while making a connection from multiple databases-

instead of using this:

with connection['configuration'].cursor() as cursor:

Use this One:

with connections['my_db_alias'].cursor() as cursor: