Django视图中的原始SQL查询

时间:2011-05-09 01:26:04

标签: django django-models django-views django-queryset

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

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

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

5 个答案:

答案 0 :(得分:41)

The Django Documentation is really really good.您基本上有两个选项来执行原始SQL。您可以使用Manager.raw()执行返回模型实例的原始查询,也可以避免使用模型层并直接执行自定义SQL。

使用raw()经理:

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

如果要直接绕过模型层,可以使用代表默认数据库连接的django.db.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

答案 1 :(得分:41)

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

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

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

答案 2 :(得分:2)

如果使用的是PostgreSQL,则可以在一个查询中完成。 如果没有,您可以相应地更改查询并获取结果。

from django.db import connection
from app.models import Picture

def results(request):
    with connection.cursor() as cursor:
        query = """
        SELECT count(*) as all_count, 
        count(*) FILTER(WHERE vote = 'yes') as yes_count
        FROM people_person;
        """
        cursor.execute(query)
        row = cursor.fetchone()
        all_count, yes_count = row

答案 3 :(得分:1)

你可以尝试这个

Picture.objects.raw("SELECT 1 as id ,"\
 "(SELECT  count(*) as yes FROM people_person WHERE vote='yes') as yes ,"\
 "(SELECT  count(*) FROM people_person WHERE vote='no') as no ,"\
 "(SELECT  count(*) FROM people_person WHERE vote='all') as all ")

答案 4 :(得分:0)

具有特定数据库名称的原始sql:

from django.db import connections
cursor = connections['database_name'].cursor()
cursor.execute("select * from table_name")

database_name =我们创建的任何数据库

table_name =我们创建的任何表名