error to pass value in query Django
<p>Hi everyone I have problem with this query in Django</p>

<pre><code>  projects_name = str(kwargs['project_name']).split(',')
  status = str(kwargs['status'])
  list_project = tuple(projects_name)
     opc_status = {'jobs_running':'running', 'jobs_pending':'pending', 'cpus_used':'cpu'}
      if status in opc_status.values():
        key = list(opc_status.keys())[list(opc_status.values()).index(status)] + ', entry_dt' 
      else:
        key='*' 

      db = MySQLdb.connect(host='..', port=, user='..', passwd='..', db='..')
      try:
        cursor = db.cursor()
        cursor.execute('SELECT %s FROM proj_cpus WHERE project in %s', key, list_project])
</code></pre>

<p>the first params of the query must be <code>*</code> or something like <code>jobs_pending, entry_dt</code></p>

<p>but query return this error</p>

<pre><code>tuple index out of range
</code></pre>

<p>Any idea about how to create the query correctly?</p>

<p>You could try this:</p>

<pre><code># Build a comma-separated string of all items in list_project
data_list = ', '.join([item for item in list_project])

query = 'SELECT %s FROM proj_cpus WHERE project in (%s)'

# Supply the parameters in the form of a tuple
cursor.execute(query, (key, data_list))
</code></pre>

<p><code>cursor.fetchall()</code> will always return data in tuples like you have observed in comments, it is not because there is an issue with the query. To convert to json you could do something like the following (<code>row_counter</code> is just a placeholder to make sure that there is a unique key for every entry).</p>

<pre><code>import json

key = '*'
data_list = ', '.join([item for item in list_project])

query = 'SELECT %s FROM proj_cpus WHERE project in (%s)'
cursor.execute(query, (key, data_list))
all_rows = cursor.fetchall()
row_headings = [header[0] for header in cursor.description]

row_counter = 0
all_rows_container = {}

for item in all_rows:
    item_dict = {row_headings[x]: item[x] for x in range(len(row_headings))}
    all_rows_container[row_counter] = item_dict
    row_counter += 1

json_data = json.dumps(all_rows_container)
print json_data
</code></pre>

<p>NOTE: the above may throw <code>IndexError</code> if the query is not with <code>key = '*'</code> because I think <code>row_headings</code> will contain all of the schema for the table, even for values that you did not select in the query. However, it should be sufficient to demonstrate the approach and you can tailor it in the event that you pick specific columns only.</p>

python django