例如,您有如下所示的“人员(Person)”模型:
Person
model。
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=30)
然后,您可以使用cursor.execute()
运行原始SQL查询,并使用cursor.fetchall()
获取结果,如果没有更多结果,则cursor.fetchall()
将返回[]
,如下所示。 *文档中对此进行了更详细的说明:
from django.db import connection
from django.http import HttpResponse
def test(request):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM store_person;")
for row in cursor.fetchall():
print(row)
print(cursor.fetchall())
return HttpResponse("Test")
控制台输出:
(1, 'Tom')
(2, 'David')
(3, 'Lisa')
[]
此外,您还可以使用cursor.fetchone()
来获取结果。如果没有更多的结果,cursor.fetchone()
将返回None
,如下所示:
from django.db import connection
from django.http import HttpResponse
def test(request):
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM store_person;")
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchone())
return HttpResponse("Test")
在控制台上输出:
(1, 'Tom')
(2, 'David')
(3, 'Lisa')
None
而且,您还可以像下面这样使用事务(transaction):
from django.db import transaction
from django.db import connection
from django.http import HttpResponse
@transaction.atomic
def test(request):
with connection.cursor() as cursor:
cursor.execute('''SELECT * FROM store_person;''')
for row in cursor.fetchall():
print(row)
return HttpResponse("Test")
或者:
from django.db import transaction
from django.db import connection
from django.http import HttpResponse
def test(request):
with transaction.atomic():
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,
},
}
然后,根据以下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