I want to log the raw SQL statements in my Django testcases.
I can see the INSERT sql statements, but I can't see the SELECT sql statements in the log.
I want to see every SQL statement in the log, whether it is CREATE, SELECT, UPDATE or something else.
Output
$ python manage.py test
<OUTPUT OMITTED>
Found 1 test(s).
Running tests...
----------------------------------------------------------------------
[{'sql': 'INSERT INTO "myapp_testtabletwo" ("test_field") VALUES (\'abc\') RETURNING "myapp_testtabletwo"."id"', 'time': '0.001'}]
.
----------------------------------------------------------------------
Ran 1 test in 0.113s
OK
Destroying test database for alias 'default'...
Closing active connection
tests.py
from django.db import connection
from my_app.models import TestTableTwo
class DatabaseExampleTests(TestCase):
databases = '__all__'
def test_example(self):
with CaptureQueriesContext(connection) as ctx:
created_object = TestTableTwo.objects.create(test_field="abc")
all_objects = TestTableTwo.objects.all()
print(ctx.captured_queries)
models.py
from django.db import models
class TestTableTwo(models.Model):
id = models.AutoField(primary_key=True)
test_field = models.CharField(max_length=100, blank=True, null=True)
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': "testpostgres",
'USER': "postgres,
'PASSWORD': "password",
'HOST': "postgres"
}
}
Version
$ python -V
Python 3.9.15
$ pip list
# output omitted
Package Version
---------------------- ---------
Django 4.1
psycopg2 2.9.5
Edit:
When I change all_objects = TestTableTwo.objects.all()
to print(TestTableTwo.objects.all())
, I see the SELECT sql statement in the log.
But I don't understand the reason, why it works with the print()
statement.