Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
Django

Django Raw Sql Queries

2022-07-20

When your model query API don't go well or you want more performance, you can use raw SQL queries in Django. The Django Object Relational Mapper (ORM) helps bridge the gap between the database and our code Performing raw queries.

app/model.py

class employee(models.Model):

    name = models.CharField(max_length=20)

    position = models.CharField(max_length=20)

    sal = models.IntegerField()

Select statment:

>>> emp_list=employee.objects.raw('select * FROM blogapp_employee')

SQL statement in .raw() return a set of rows from the database if not return rows, error will result.

>>> for i in emp_list:

  ...    i.name

  ... 

  u'ravi'

  u'john'

  u'pheebi'

Above work same as model_name.objects.all().

MyModel.objects.all() is a very simplyfied ORM. This code will return the entire contents of the database table, same as running: select * from MyModel.

Only use .raw() method when you con't do task with which Django QuerySet.

Update, Delete With sql(Using cursor)

>>>from django.db import connection

  >>>cursor = connection.cursor()

  >>>cursor.execute("UPDATE tablename SET field=value, .. WHERE .'condition'. ")

    >>>cursor.execute("DELETE tablename SET field=value, .. WHERE .'condition'. ")

To see What are the sql queries django running:

>>> from django.db import connection
  >>> connection.queries
  [{'sql': 'SELECT * FROM blog_employee',
  'time': '0.001'}]

  #sql -- The raw SQL statement
 #time -- How long the statement took to execute, in seconds.

You can see django orm query equalent to sql qeury

>>> q = employee.objects.all()

  >>> q

  []

  >>> print q.query

  SELECT "blogapp_employee"."id", "blogapp_employee"."name", "blogapp_employee"."position", "blogapp_employee"."sal" FROM "blogapp_employee"