Skip to content

Instantly share code, notes, and snippets.

@j4mie
Created July 19, 2018 12:13
Show Gist options
  • Save j4mie/2b230f55065df9e2844bb2c6882de5cc to your computer and use it in GitHub Desktop.
Save j4mie/2b230f55065df9e2844bb2c6882de5cc to your computer and use it in GitHub Desktop.
Context manager / decorator for stopping the Django ORM from making queries in a given block of code
from contextlib import contextmanager
from django.db import connections
class QueriesDisabledError(Exception):
pass
def fake(*args, **kwargs):
raise QueriesDisabledError()
def apply_monkeypatch():
for connection in connections.all():
connection._real_create_cursor = connection.create_cursor
connection.create_cursor = fake
def remove_monkeypatch():
for connection in connections.all():
connection.create_cursor = connection._real_create_cursor
del connection._real_create_cursor
@contextmanager
def queries_disabled():
apply_monkeypatch()
try:
yield
finally:
remove_monkeypatch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment