python Django视图中的原始SQL查询

8ftvxx2r  于 2022-12-10  发布在  Python
关注(0)|答案(7)|浏览(235)

如何在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函数是什么样子的?

zazmityj

zazmityj1#

>>> 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子句筛选赞成票:

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

ibps3vxo2#

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
sczxawaw

sczxawaw3#

如果您使用的是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
kb5ga3dv

kb5ga3dv4#

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

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

database_name =用户创建的任何数据库
table_name =用户创建的任何表名

uklbhaso

uklbhaso5#

你可以试试这个

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

rt4zxlrg6#

**raw()**方法可用于执行返回模型示例的原始sql查询。

books = Book.objects.raw('SELECT id,name,pages FROM app_books WHERE pages>100')

如果你可能执行的查询没有清晰地Map到模型.. django.db.connection代表默认的数据库连接,所以调用**connection.cursor()**来使用数据库连接。请参阅文档

from django.db import connection
def my_custom_sql(self):
    with connection.cursor() as cursor:
        cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
        cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
        row = cursor.fetchone()

    return row
q8l4jmvw

q8l4jmvw7#

例如,您有**Person型号**,如下所示:

# "store/models.py"

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=30)

然后,您可以使用cursor.execute()运行原始SQL查询,并使用cursor.fetchall()获得如下所示的结果。*文档对此进行了详细说明:

# "store/views.py"

from django.db import connection
from django.http import HttpResponse

def test(request):
    with connection.cursor() as cursor:
        cursor.execute('''SELECT * FROM store_person;''') # Here

        for row in cursor.fetchall(): # Here
            print(row)

    return HttpResponse("Test")

控制台上的输出:

(1, 'Tom')
(2, 'David')
(3, 'Lisa')

并且,您还可以使用交易,如下图所示:

# "store/views.py"

from django.db import transaction
from django.db import connection
from django.http import HttpResponse

@transaction.atomic # Here
def test(request):
    with connection.cursor() as cursor:
        cursor.execute('''SELECT * FROM store_person;''')

        for row in cursor.fetchall():
            print(row)

    return HttpResponse("Test")

或者:

# "store/views.py"

from django.db import transaction
from django.db import connection
from django.http import HttpResponse

def test(request):
    with transaction.atomic(): # Here
        with connection.cursor() as cursor:
            cursor.execute('''SELECT * FROM store_person;''')

            for row in cursor.fetchall():
                print(row)

    return HttpResponse("Test")

或者:

DATABASES = {
    'default':{
        'ENGINE':'django.db.backends.postgresql',
        'NAME':'postgres',
        'USER':'postgres',
        'PASSWORD':'admin',
        'HOST':'localhost',
        'PORT':'5432',
        'ATOMIC_REQUESTS': True, # Here
    },
}

以下这些日志是PostgreSQL查询日志。* 我使用了PostgreSQL我的答案解释了如何记录包含事务查询的PostgreSQL查询

[21200] LOG:  duration: 0.008 ms  statement: BEGIN
[21200] LOG:  duration: 1.232 ms  statement: SELECT * FROM store_person;
[21200] LOG:  duration: 0.024 ms  statement: COMMIT

相关问题