Counting calls to Django QuerySet methods

Posted on October 06, 2017 · 1 min read

Yesterday, I spent some time working on a test that needed to verify the delete method was called a certain number of times for a Django model. In the past we have used the assertNumQueries() method, but it always comes with some flakiness/tediousness (especially if we have to worry about queries made by middleware and/or authentication handlers). When we use this method, we generally run the test once, get the query count and use that as the expected count for future tests. In this case, that number was 33, only 5 of which I cared about for my test. It seemed odd to have an expected query count that wasn’t tied solely to my tests. Thus, I set out to find a way to solely count the number of deletions.

The mock library ended up not working out for me, but I came across a decorator that wraps the method, adding a counter that tracks the number of invocations. The original decorator can be seen at

Here it is in action.