是否可以停止Django在原始SQL参数周围添加引号? [英] Is it possible to stop Django adding quotes around raw SQL params?

查看:40
本文介绍了是否可以停止Django在原始SQL参数周围添加引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django的原始SQL功能(如果参数是字符串,则在传递给SQL查询的任何参数周围都添加单引号).

Django's raw SQL feature adds single quote marks around any parameters you pass into the SQL query, if the parameters are strings.

当我需要执行以下查询时,这对我不利:

This breaks for me when I need to do a query like this:

SELECT * FROM表WHERE ID IN(%s)

参数是一个字符串,例如'1,2,3',因此Django将查询呈现为:

The param is a string, such as '1,2,3', so Django renders the query as:

SELECT * FROM表WHERE ID IN('1,2,3')

这些参数周围的引号会破坏查询.

Those quotes around the param break the query.

在我看来,Django强迫我使用字符串插值(即,在将字符串用于原始查询之前将参数注入字符串中),但是文档清楚地表明我们不应该这样做.

It seems to me Django is forcing me to use string interpolation (ie injecting the params into the string before it's used in the raw query), yet the docs clearly state we should not do that.

从文档中

使用params参数可以完全保护您免受SQL注入攻击,这是攻击者将任意SQL注入其中的常见漏洞您的数据库.如果您使用字符串插值,迟早会成为SQL注入的受害者.只要你记得一直使用params参数将受到保护.

Using the params argument 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 argument you’ll be protected.

有没有办法关闭引号?如果我们想要报价,我们可以将其添加,不是吗?(例如WHERE名称='%s')

Is there a way to turn OFF the quotes? If we want quotes we can just add them, no? (eg WHERE name = '%s')

推荐答案

Django原始查询采用

The Django raw query takes in parameters as a single list or dictionary. So in this case, you should be invoking your raw query like this:

YourModel.objects.raw('SELECT * FROM table WHERE id in%s',[(1,2,3,4,5,...)])

这篇关于是否可以停止Django在原始SQL参数周围添加引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆