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>The best thing to do is to use Django's ORM API to make queries:</p>

<pre><code>from foo.models import ProjCpu
...
projects_name = ...
...
ProjCpu.objects.filter(project__in=projects_name)
</code></pre>

<p>You can read everything about it in the Django documentation.</p>

<p>Basically That's all you need to know, but if you want to know more about the error you got, you are welcome to keep reading.</p>

<p>The error you got was caused by wrong usage of string formatting.
To pass multiple arguments to string formatting you use a tuple, like so:</p>

<pre><code>print("the %s, the %s and the %s" % ("good", "bad", "ugly"))
</code></pre>

<p>Since you supplied a tuple to the string formatting, python tried to format the items in the tuple as separate, multiple arguments. And because you specified only one "%s" in the string, there was an error.</p>

<p>In order to supply a tuple as the sole argument you must put it as the only member of another tuple:</p>

<pre><code>my_tuple = (1, 2, 3)
print("tuple: %s" % (my_tuple,))
</code></pre>

<p>or just use <code>.format</code>:</p>

<pre><code>print("tuple: {}".format(my_tuple))
</code></pre>

<p>In your case doing <code>query = "SELECT * FROM proj_cpus WHERE project in '%s'"  % (projects_name,)</code> will no longer raise an error. But as mentioned before, just use Django's ORM for queries.</p>

python django