【问题标题】:Django unable to get values from database in another table [duplicate]Django无法从另一个表中的数据库中获取值[重复]
【发布时间】:2019-04-08 13:47:12
【问题描述】:

我需要在 django 中加入表格。我正在使用游标对象从数据库中获取所有值。

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)

模型.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 是配置数据库中的一个表。无法获取集成中的所有值。 错误:使用 connection['configuration'].cursor() 作为光标: TypeError: 'DefaultConnectionProxy' 对象不可下标

【问题讨论】:

  • 为什么你认为connection['configuration'] 应该是有效的?
  • 使用connections 而不是connection
  • @dirkgroten with connections['configuration'].cursor() 作为光标:NameError: name 'connections' is not defined
  • 当然需要导入。阅读docs。

标签: python mysql django


【解决方案1】:

您正在使用不同的数据库“配置”。您应该在从多个数据库建立连接时使用以下代码-

而不是使用这个:

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

使用这个:

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

【讨论】:

    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 2021-09-18
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多