Prevent RawSQL injection in Django

In my Django application I am using RawSQL queries as an additional security layer, I want to parse every RawSQL query to prevent delete or update operation.

example : There are some automated jobs scheduled from django admin panel which utilise the RawSQL queries while execution I need a method to add a validation layer over the rawsql execution so that I can prevent execution of any delete, update etc queries.

To prevent SQL injection in Django, you should always use parameterized queries when working with the database. This means using placeholders in your SQL queries and passing the values as separate parameters.

For example, instead of using string concatenation to build a query:

cursor.execute("SELECT * FROM myapp_mymodel WHERE name='" + user_input + "'")

You should use placeholders and pass the values as separate parameters:

cursor.execute("SELECT * FROM myapp_mymodel WHERE name=%s", [user_input])

Django's ORM provides a high-level, Pythonic API for interacting with the database. It automatically escapes any values passed to it, so you don't need to worry about SQL injection when using the ORM.

You should also make sure to never use string concatenation or interpolation to build raw SQL queries, since this can open your application up to SQL injection attacks. Instead, use the ORM's query construction API, which is designed to prevent SQL injection.

For example, instead of using raw SQL:

MyModel.objects.raw("SELECT * FROM myapp_mymodel WHERE name='" + user_input + "'")

You should use the ORM's query construction API:

MyModel.objects.filter(name=user_input)

It's also good practice to validate inputs from user and to limit the result set by using limit() and offset() to prevent large data retrieval by attackers.

Back to Top