diff --git a/cachalot/monkey_patch.py b/cachalot/monkey_patch.py index 1013617..8713dff 100644 --- a/cachalot/monkey_patch.py +++ b/cachalot/monkey_patch.py @@ -26,7 +26,7 @@ from .cache import cachalot_caches from .settings import cachalot_settings from .utils import ( _get_query_cache_key, _invalidate_tables, - _get_table_cache_keys, _get_tables_from_sql) + _get_table_cache_keys, _get_tables_from_sql, RandomQueryException) WRITE_COMPILERS = (SQLInsertCompiler, SQLUpdateCompiler, SQLDeleteCompiler) @@ -84,18 +84,17 @@ def _patch_compiler(original): def inner(compiler, *args, **kwargs): execute_query_func = lambda: original(compiler, *args, **kwargs) if not cachalot_settings.CACHALOT_ENABLED \ - or isinstance(compiler, WRITE_COMPILERS) \ - or (not cachalot_settings.CACHALOT_CACHE_RANDOM - and '?' in compiler.query.order_by): + or isinstance(compiler, WRITE_COMPILERS): return execute_query_func() try: cache_key = _get_query_cache_key(compiler) - except EmptyResultSet: + table_cache_keys = _get_table_cache_keys(compiler) + except (EmptyResultSet, RandomQueryException): return execute_query_func() return _get_result_or_execute_query( - execute_query_func, cache_key, _get_table_cache_keys(compiler)) + execute_query_func, cache_key, table_cache_keys) inner.original = original return inner diff --git a/cachalot/utils.py b/cachalot/utils.py index a0b2fd6..631871f 100644 --- a/cachalot/utils.py +++ b/cachalot/utils.py @@ -18,6 +18,10 @@ from .settings import cachalot_settings from .signals import post_invalidation +class RandomQueryException(Exception): + pass + + def get_query_cache_key(compiler): """ Generates a cache key from a SQLCompiler. @@ -88,8 +92,11 @@ def _find_subqueries(children): def _get_tables(query, db_alias): + if '?' in query.order_by and not cachalot_settings.CACHALOT_CACHE_RANDOM: + raise RandomQueryException + tables = set(query.table_map) - tables.add(query.model._meta.db_table) + tables.add(query.get_meta().db_table) subquery_constraints = _find_subqueries(query.where.children + query.having.children) for subquery in subquery_constraints: