What's the best way to find the number of database accesses being done?

10 views
Skip to first unread message

Don Baldwin

unread,
Jul 23, 2019, 12:19:03 PM7/23/19
to Django users
I have a function that runs some database queries and updates.  In the test code for that function, I'd like to check out many times the database is actually being hit.  Does Django provide a way to get that information?

Thanks,
Don

Simon Charette

unread,
Jul 23, 2019, 2:37:40 PM7/23/19
to Django users
Hello Don,

Django logs all database queries to the django.db.backends logger. It is not
redirected to STDOUT when using the default settings.LOGGING configuration
but you can enable it yourself[0].

If you wan to assert against a fixed number of queries you can use the
assertNumQueries context manager[1] provided by SimpleTestCase and its
subclasses to do that.

For an easy to setup and per-view breakdown of the number of queries I
suggest you install the django-debug-toolbar[2] and enable the SQL panel.

For more details about optimizing database accesses within a Django project
I suggest you have a look at the dedicated section of the documentation[3].
I've filed a ticket to make sure bulk_update is also mentioned in this section
of the documentation.

Cheers,
Simon

Don Baldwin

unread,
Jul 24, 2019, 10:17:14 AM7/24/19
to django...@googlegroups.com
Thanks for the quick response Simon.  This looks to be very informative.  It will take me a while to digest all of it, but I've already gotten logging working for my queries.  Very helpful.

Thanks,
Don

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/cywNQX35caw/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bf8c2c46-40b7-477a-8635-9da5c766bb7d%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages