How to write raw sql queries in Django?

There are situations where SQL queries become too complex to be effectively written using Django's ORM—especially when dealing with advanced joins, subqueries, window functions, or database-specific features. In such cases, it's more practical and efficient to write the SQL query manually and execute it directly within Django. Django provides a convenient method called raw() that allows you to run raw SQL SELECT queries directly. This method is simple to use and still returns data as model instances, giving you the benefits of Django models along with the flexibility of custom SQL. Using raw() helps you handle complex queries while maintaining a clean integration with your application.



# models.py
class Student(models.Model):
    name = models.CharField(max_length=255)
    stud_class = models.CharField(max_length=255)
    marks = models.DecimalField(max_digits=8, decimal_places=2)

    getStudentDetails():
        query = ' SELECT * FROM student ORDER BY name DESC'
        student_details = Student.objects.raw(query)
        return student_details