Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw SQL queries in Django views

How would I perform the following using raw SQL in views.py?

from app.models import Picture  def results(request):     all = Picture.objects.all()     yes = Picture.objects.filter(vote='yes').count()     return render_to_response('results.html', {'picture':picture, 'all':all, 'yes': yes}, context_instance=RequestContext(request)) 

What would this results function look like?

like image 558
David542 Avatar asked May 09 '11 01:05

David542


People also ask

What is raw SQL query?

Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query. Raw SQL queries can return regular entity types or keyless entity types that are part of your model.

How do I get the query builder to output its raw SQL query as a string?

DB::QueryLog() works only after you execute the query using $builder->get() . If you want to get the raw query before or without executing the query, you can use the $builder->toSql() method.

What is a Django query?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


2 Answers

>>> from django.db import connection >>> cursor = connection.cursor() >>> cursor.execute('''SELECT count(*) FROM people_person''') 1L >>> row = cursor.fetchone() >>> print row (12L,) >>> Person.objects.all().count() 12 

use WHERE clause to filter vote for yes:

>>> cursor.execute('''SELECT count(*) FROM people_person WHERE vote = "yes"''') 1L 
like image 82
dting Avatar answered Oct 01 '22 12:10

dting


The Django Documentation is really really good. You have basically two options to execute raw SQL. You can use Manager.raw() to perform raw queries which return model instances, or you can avoid the model layer and execute custom SQL directly.

Using the raw() manager:

>>> for p in Person.objects.raw('SELECT * FROM myapp_person'): ...     print p John Smith Jane Jones 

If you want to bypass the model layer directly you can use django.db.connection which represents the default database connection:

def my_custom_sql():     from django.db import connection, transaction     cursor = connection.cursor()      # Data modifying operation - commit required     cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])     transaction.commit_unless_managed()      # Data retrieval operation - no commit required     cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])     row = cursor.fetchone()      return row 
like image 24
zeekay Avatar answered Oct 01 '22 10:10

zeekay