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