In Django, is there an easy way to test that a model field on an object has already been queried from the database (e.g. an object coming from a foreign-key relationship)?
I would like to make an assertion like this in one of my tests to ensure that accessing a particular attribute on one of my objects won't trigger an additional database query.
In the particular case of a ForeignKey, you can check the existence of the _FOO_cache
attribute. For instance, if your Employee object has a ForeignKey to Company, then if my_employee.company
is populated then my_employee._company_cache
will exist, so you can do hasattr(my_employee, '_company_cache')
.
You can use TestCase.assertNumQueries.
To check that obj.accessor
doesn't hit the database:
# context manager version
with self.assertNumQueries(0):
obj.accessor
# function version
self.assertNumQueries(0, lambda: obj.accessor)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With