Search code examples
pythonsqldjangodjango-modelsdjango-views

How to perform 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?


Solution

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