Search code examples
sqldjangosql-injection

Django,if using raw SQL, what steps should I take to avoid SQL injection attacks?


I have read that ORM's should minimise the possibilities of SQL injection attacks. However in Django, sometimes the ORM is somewhat limited, and I need to use raw SQL. What steps should I take to avoid SQL injection attacks?

Currently I would know to check for semicolons in the query string, but not much else. If I use parametrised queries, will this solve the problem? Are there any libraries to pass the string to, that will check it for me?


Solution

  • The documentation states the following:

    If you need to perform parameterized queries, you can use the params argument to raw():

    >>> lname = 'Doe'
    >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
    

    params is a list or dictionary of parameters. You’ll use %s placeholders in the query string for a list, or %(key)s placeholders for a dictionary (where key is replaced by a dictionary key, of course), regardless of your database engine. Such placeholders will be replaced with parameters from the params argument.

    This is also the standard way to pass parameters using Python's DB-API, which will sanitize your queries correctly.

    Whatever you do, don't do string interpolation.