如何在Django python的原始sql中插入参数

2024-04-29 02:13:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码

myquery =   '''SELECT * from users 
               where id = 10 and
               city = 20 and 
               state = 30'''

现在我想用三个变量来代替

var_id = bla
var_city = bla
var_state = bla

Tags: andfromid密码cityvarwhereselect
2条回答

使用^{} argument to ^{}

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])

params是参数列表。您将在查询字符串中使用%s占位符(不管您的数据库引擎是什么);它们将替换为params列表中的参数。


Django docs的重要说明:

Warning Do not use string formatting on raw queries!

It's tempting to write the above query as:

>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)

Don't.

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.

您还可以在查询中使用字典和变量:

my_dict = {
   'id': 10,
   'city': 20,
   'state': 30
} 

mymodel.objects.raw('''SELECT * from users 
                       where id = %(id)s and
                       city = %(city)s and 
                       state = %(state)s ''', my_dict)

你可以在这里阅读更多内容:https://docs.djangoproject.com/en/1.10/topics/db/sql/#passing-parameters-into-raw

相关问题 更多 >