Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one assert in Django that a model field has already been populated from the DB?

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.

like image 929
cjerdonek Avatar asked Jan 13 '14 13:01

cjerdonek


2 Answers

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').

like image 162
Daniel Roseman Avatar answered Sep 29 '22 19:09

Daniel Roseman


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)
like image 37
Nigel Tufnel Avatar answered Sep 29 '22 19:09

Nigel Tufnel