Django raw SQL queries for complex operations

12735
0

For queries too complex for the ORM, I use raw SQL. The raw() method returns model instances. I use cursor.execute() for non-model queries. I always use parameterized queries to prevent SQL injection—never string interpolation. For reporting, raw SQL is often clearer than complex ORM chains. I document why raw SQL is needed so future developers understand. For database-specific features like window functions, raw SQL is sometimes the only option. I test raw queries against multiple database backends if the app supports them.