Django Raw Sql Queries

Reading Time : ~ .

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, transaction

  >>>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"
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Sending emails using sendgrid on heroku for a Django App Vinisha Naladala

Integrate Sendgrid API to your Heroku app to deliver simplified emails like any notification emails, user signups etc.

Continue Reading...
Django search with haystack and whoosh Ashwin Kumar

Haystack is a Django plugin to allow text search, while Whoosh is a pure Python search backend and it provides a library of classes and ...

Continue Reading...
Custom Decorators To Check User Roles And Permissions In Django Ramya Ambati

A decorator is a function that takes another function and returns a newer,prettier version of that function.

To know more about decorators in python see ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties