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 index binary files in django haystack Ramya Ambati

Now we are going to index text content which is stored in structured files such as PDFs, Microsoft Office documents, images, etc using haystack and ...

Continue Reading...
Integration Of GitHub API with python django Nikhila Mergu

Using Github integration, we can get the user verified email id, general information, git hub URL, id, disk usage, public, private repo's, gists and followers, ...

Continue Reading...
Preserve file names with sorl for better SEO Ashwin Kumar

We use sorl-thumbnail for scaling images by keeping the original one intact. Sorl proven to be great tool for generating different sized images throughout website. ...

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