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
How to customize Django Oscar Models, Views and URL's Chaitanya Kattineni

In order to customize models, views and urls, you need to fork an Oscar core app in which model/view resides. Then you should be able ...

Continue Reading...
Integrating Gitlab in django project with gitlab api for gitlab authentication and access Nikhila Mergu

This is a simple way to integrate gitlab authentication in your django apps.

We can get user verified email id, general information, git lab URL ...

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...

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