<p>使用<a href="https://docs.djangoproject.com/en/dev/topics/db/sql/#passing-parameters-into-raw" rel="noreferrer">^{<cd1>} argument to ^{<cd2>}</a>:</p>
<pre><code>var_id = 10
var_city = 20
var_state = 30
mymodel.objects.raw('''SELECT * from users
where id = %s and
city = %s and
state = %s ''', [var_id, var_city, var_state])
</code></pre>
<p><code>params</code>是参数列表。您将在查询字符串中使用<code>%s</code>占位符(不管您的数据库引擎是什么);它们将替换为params列表中的参数。</p>
<hr/>
<p>Django docs的重要说明:</p>
<blockquote>
<p>Warning
Do not use string formatting on raw queries!</p>
<p>It's tempting to write the above query as:</p>
</blockquote>
<pre><code>>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)
</code></pre>
<blockquote>
<p>Don't.</p>
<p>Using the params list completely protects you from SQL injection attacks, a common exploit where attackers inject arbitrary SQL into your database. If you use string interpolation, sooner or later you'll fall victim to SQL injection. As long as you remember to always use the params list you'll be protected.</p>
</blockquote>