Create a query with Django
<p>Hi everyone I and try to do a query with the params pass by URL in my case the uRL is like</p>

<pre><code>http://127.0.0.1:8000/api/cpuProjects/cpp/es
http://127.0.0.1:8000/api/cpuProjects/cpp,ad/es
</code></pre>

<p>My code to create the query is like this </p>

<pre><code>def findElem(request, **kwargs):
  projects_name = str(kwargs['project_name']).split(',')
  status = str(kwargs['status'])
  list_project = tuple(projects_name)
  print(list_project)
  query = "SELECT * FROM proj_cpus WHERE project in '%s'"  % projects_name
  print(query)
  result = run_query(query)
</code></pre>

<p>the first return this query</p>

<pre><code>SELECT * FROM proj_cpus WHERE project in '['cpp']'
</code></pre>

<p>the second one  has to by a query like this</p>

<pre><code>SELECT * FROM proj_cpus WHERE project in '['cpp', 'ad']'
</code></pre>

<p>In this case when I execute the query return that I have a error in the syntax, yes I know the [] is no correct</p>

<p>So I convert my params in a tuple 
so now the query is like that</p>

<p>and the error is </p>

<pre><code>SELECT * FROM proj_cpus WHERE project in ('cpp')
SELECT * FROM proj_cpus WHERE project in ('cpp', 'ad')

not all arguments converted during string formatting
</code></pre>

<p>What is the best way to create the query?</p>

<p>Thanks in advance</p>

<p>Im sorry to say that, but passing your variables directly into a query is dangerous in every language. Try something more like this. Django will take care for you to escape your arguments proper, otherwise you get SQL injection possibilities:</p>

<pre><code>from foo.models import CPUSModel

projects_name = ... whatever you did to get a tuple ...

results = CPUSModel.objects.raw('SELECT * FROM proj_cpus WHERE project in %s', [tuple(projects_name),])
list(results)
</code></pre>

<p>For more questions about django raw queries, you can check <a href="https://docs.djangoproject.com/en/1.10/topics/db/sql/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/db/sql/</a></p>

python django