анализ нескольких выходных записей sql (с использованием объекта cursor) в django

#python #mysql #django

#python #mysql #django

Вопрос:

В django я использовал концепцию connections для извлечения данных. Выходные данные содержат несколько записей, которые необходимо проанализировать через него.

 cursor = connections['configuration'].cursor()
   cursor.execute("SELECT DISTINCT(integrations.trail_userid),integrations.environment, integrations.endpoint, integrations.connectivity_status, integrations.subscription_status from integrations INNER JOIN list_integration_tools ON integrations.endpoint = list_integration_tools.endpoint WHERE integrations.`trail_username`='ambika02'")
   row = cursor.fetchall()
   print(row)
  

Это мой КОД
Результат строки ((30, None, ‘snow’, ‘production’, ‘dev’), (30, None, ‘jira’, ‘production’, ‘production’))

Мне нужно проанализировать строку, чтобы получить все значения

строка [0] дает мне первую запись (30, None, ‘snow’, ‘production’, ‘dev’), Но как мне проанализировать первую запись

Ответ №1:

Вы даже можете извлечь все имя атрибута вместе с его значениями из таблицы, используя это, в список словаря, что также поможет вам при синтаксическом анализе в шаблоне Django, а также позволит избежать 2 циклов как в представлениях, так и в шаблоне

 def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
     columns = [col[0] for col in cursor.description]
     return [
            dict(zip(columns, row))
            for row in cursor.fetchall()
        ]

    cursor = connections['configuration'].cursor()
    cursor.execute("SELECT DISTINCT(integrations.trail_userid), integrations.environment, 
                             integrations.endpoint, integrations.connectivity_status, 
                             integrations.subscription_status 
                    FROM integrations INNER JOIN list_integration_tools 
                    ON integrations.endpoint = list_integration_tools.endpoint 
                    WHERE integrations.`trail_username`='ambika02'")

   all_data = dictfetchall(cursor)
  

Ответ №2:

Вы можете использовать цикл for и перебирать строки. Каждая строка является кортежем, поэтому вы можете получить доступ к значениям по его индексу.

Смотрите пример ниже:

 for subrow in row:
    subrow[0]
    subrow[1]
    subrow[2]
    subrow[3]
    subrow[4]
  

Если вы хотите получить доступ к первой записи, попробуйте:

 row[0][0]
row[0][1]
row[0][2]
row[0][3]
row[0][4]