Django 视图中的原始 SQL 查询 [英] Raw SQL queries in Django views

查看:31
本文介绍了Django 视图中的原始 SQL 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何在 views.py 中使用原始 SQL 执行以下操作?

from app.models 导入图片定义结果(请求):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))

这个 results 函数会是什么样子?

解决方案

>>>从 django.db 导入连接>>>游标 = connection.cursor()>>>cursor.execute('''SELECT count(*) FROM people_person''')1L>>>行 = cursor.fetchone()>>>打印行(12L,)>>>Person.objects.all().count()12

使用 WHERE 子句过滤对 yes 的投票:

<预><代码>>>>cursor.execute('''SELECT count(*) FROM people_person WHERE vote = "yes"''')1L

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?

解决方案

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

这篇关于Django 视图中的原始 SQL 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆