如何在 Django 视图中执行原始 SQL 查询?

发布于 2024-11-06 00:35:27 字数 449 浏览 1 评论 0原文

如何在 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)
    )

这个结果函数会是什么样子?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

微凉 2024-11-13 00:35:27
>>> 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
>>> 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
不疑不惑不回忆 2024-11-13 00:35:27

Django 文档真的非常好。 基本上你有两种选择执行原始 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

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
つ低調成傷 2024-11-13 00:35:27

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

from django.db import connection

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

It can be done within one query if you are using PostgreSQL.
If not, you can change the query accordingly and get the results.

from django.db import connection

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
风吹过旳痕迹 2024-11-13 00:35:27

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

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

# manually close the cursor if you are done!
cursor.close()
database_name = Any database created by us
table_name = Any table name created by us

Raw sql with the specific database name:

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

# manually close the cursor if you are done!
cursor.close()
database_name = Any database created by us
table_name = Any table name created by us
彼岸花ソ最美的依靠 2024-11-13 00:35:27

你可以试试这个

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

You Can try this

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 ")
迷路的信 2024-11-13 00:35:27

raw() 方法可用于执行返回模型实例的原始 sql 查询..查看文档

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

如果您可能执行未完全映射到模型的查询..
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

raw() method can be used to perform raw sql queries that return model instances ..see docs

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

if you might perform queries that don't map cleanly to models ..
django.db.connection represents default database connection so call
connection.cursor() to use database connection. see docs

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
揪着可爱 2024-11-13 00:35:27

例如,您有如下所示的 Person 模型

# "store/models.py"

from django.db import models

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

然后,您可以使用 cursor.execute() 运行原始 SQL 查询 并使用 cursor.fetchall() 获取结果,如果没有更多结果,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)

        print(cursor.fetchall()) # []

    return HttpResponse("Test")

控制台上的输出:

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

并且,您还可以使用 cursor.fetchone() 来获取结果,如果没有更多结果,则使用 cursor.fetchone () 返回 None 如下所示:

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

        print(cursor.fetchone()) # (1, 'Tom')
        print(cursor.fetchone()) # (2, 'David')
        print(cursor.fetchone()) # (3, 'Lisa')
        print(cursor.fetchone()) # None

    return HttpResponse("Test")

控制台输出:

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

并且,您还可以使用 transaction 如下所示:

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

For example, you have Person model as shown below:

# "store/models.py"

from django.db import models

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

Then, you can run the raw SQL query with cursor.execute() and get the result with cursor.fetchall() and if there is no more result, cursor.fetchall() returns [] as shown below. *The documentation explains more about it:

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

        print(cursor.fetchall()) # []

    return HttpResponse("Test")

Output on console:

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

And, you can also use cursor.fetchone() to get the result and if there is no more result, cursor.fetchone() returns None as shown below:

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

        print(cursor.fetchone()) # (1, 'Tom')
        print(cursor.fetchone()) # (2, 'David')
        print(cursor.fetchone()) # (3, 'Lisa')
        print(cursor.fetchone()) # None

    return HttpResponse("Test")

Output on console:

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

And, you can also use transaction as shown below:

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

Or:

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

Or:

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

Then, transaction is run according to these PostgreSQL logs below. *I used PostgreSQL and my answer explains how to log PostgreSQL queries:

[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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文