{"id":8104,"library":"django-mock-queries","title":"Django Mock Queries","description":"django-mock-queries is a Python library designed for mocking Django queryset functions in memory during testing. It provides a way to simulate Django's ORM behavior, including method chaining, Q object filtering, aggregates, and CRUD operations, without needing a live database connection. The library is actively maintained, with the current version being 2.3.0, and receives regular updates to support newer Python and Django versions.","status":"active","version":"2.3.0","language":"en","source_language":"en","source_url":"https://github.com/stphivos/django-mock-queries","tags":["Django","testing","mocking","queryset","unit-testing","orm"],"install":[{"cmd":"pip install django-mock-queries","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Core functionality is built on Django's ORM concepts. Compatible with Django 3.2, 4.x, and potentially 5.x based on recent testing.","package":"Django","optional":false}],"imports":[{"note":"The primary class for creating mock querysets.","symbol":"MockSet","correct":"from django_mock_queries.query import MockSet"},{"note":"A utility class for creating mock model instances to populate MockSet.","symbol":"MockModel","correct":"from django_mock_queries.query import MockModel"},{"note":"Used to replace the real database connection with a mock one for faster tests.","symbol":"monkey_patch_test_db","correct":"from django_mock_queries.mocks import monkey_patch_test_db"}],"quickstart":{"code":"from django.db.models import Avg, Q\nfrom django_mock_queries.query import MockSet, MockModel\n\n# Example 1: Basic filtering\nqs = MockSet(\n    MockModel(mock_name='john', email='john@gmail.com'),\n    MockModel(mock_name='jeff', email='jeff@hotmail.com'),\n    MockModel(mock_name='bill', email='bill@gmail.com'),\n)\nresults = [x for x in qs.all().filter(email__icontains='gmail.com').select_related('address')]\n# print(results) # Expected: [<MockModel: john>, <MockModel: bill>]\n\n# Example 2: Aggregation\nqs_agg = MockSet(\n    MockModel(mock_name='model s', msrp=70000),\n    MockModel(mock_name='model x', msrp=80000),\n    MockModel(mock_name='model 3', msrp=35000),\n)\nagg_result = qs_agg.all().aggregate(Avg('msrp'))\n# print(agg_result) # Expected: {'msrp__avg': 61666.666...}\n\n# Example 3: Filtering with Q objects\nqs_q = MockSet(\n    MockModel(mock_name='model x', make='tesla', country='usa'),\n    MockModel(mock_name='s-class', make='mercedes', country='germany'),\n    MockModel(mock_name='s90', make='volvo', country='sweden'),\n)\nq_results = [x for x in qs_q.all().filter(Q(make__iexact='tesla') | Q(country__iexact='germany'))]\n# print(q_results) # Expected: [<MockModel: model x>, <MockModel: s-class>]\n\n# Example 4: Creating objects\nqs_create = MockSet(cls=MockModel)\nnew_obj = qs_create.create(mock_name='my_object', foo='1', bar='a')\n# print(new_obj) # Expected: <MockModel: my_object>\n# print([x for x in qs_create]) # Expected: [<MockModel: my_object>]","lang":"python","description":"This quickstart demonstrates how to create `MockSet` instances, populate them with `MockModel` objects, and perform common queryset operations like filtering, aggregation, Q-object filtering, and creating new mock objects. It mirrors typical Django ORM interactions in an in-memory test environment."},"warnings":[{"fix":"Upgrade to Python 3.x, or pin `django-mock-queries` to a version older than 2.2.0 (e.g., `~=2.1`).","message":"Version 2.2.0 dropped support for Python 2.x. Projects still using Python 2 must remain on `django-mock-queries<2.2.0`.","severity":"breaking","affected_versions":">=2.2.0"},{"fix":"Mark tests that require a real database to skip when the mock database is active. This can often be done with decorators like `@unittest.skipIf(settings.MOCK_DB, 'Requires real DB')` or specific `django-mock-queries` features if available.","message":"When using `monkey_patch_test_db()` for in-memory tests, any tests that *require* actual database interaction will raise a `NotSupportedError`.","severity":"gotcha","affected_versions":"All versions using `monkey_patch_test_db`"},{"fix":"Ensure that `return_value` of a chained mock method is another mock queryset (e.g., `MockSet`) or a mock configured to mimic queryset behavior (e.g., `mock_queryset.filter.return_value = mock_queryset`).","message":"Chaining mock queryset methods (e.g., `Manager.filter().order_by().exists()`) requires careful handling of `return_value` to ensure each step returns a mock object that supports subsequent method calls, not a plain list.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If encountering unexpected behavior with complex filters, simplify the query for testing or manually verify the expected output. Consider testing such complex queries against a real database if fidelity is critical. Check GitHub issues for known limitations or fixes in newer versions.","message":"Complex Q-object filters, custom lookups, or specific field types (like JSONField with list values) may not be fully replicated or might return unexpected results compared to Django's actual ORM.","severity":"gotcha","affected_versions":"All versions, especially older ones"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Identify tests that require a live database. Either configure your test runner to use a real database for those specific tests, or mark those tests to be skipped when `monkey_patch_test_db()` is active.","cause":"The `monkey_patch_test_db()` function has replaced Django's database connection with a mock, and a test is attempting a real database operation.","error":"NotSupportedError: Mock database tried to execute SQL for <Model> model."},{"fix":"Ensure that any chained mock methods return another `MockSet` instance or a mock object configured to mimic a `QuerySet`'s chainable behavior. For instance, `mock_manager.filter.return_value = MockSet([...])` or if chaining itself is the goal, `mock_queryset.filter.return_value = mock_queryset`.","cause":"A mocked queryset method returned a plain Python list, and a subsequent chained queryset method (like `filter()`, `order_by()`, `exists()`) was called on it. This typically happens when `mock_object.some_method.return_value = [...]` instead of another mock queryset.","error":"AttributeError: 'list' object has no attribute 'filter'"},{"fix":"Install the library using `pip install django-mock-queries`. Ensure your virtual environment is activated if you are using one.","cause":"The `django-mock-queries` package is not installed in the current Python environment or virtual environment.","error":"ModuleNotFoundError: No module named 'django_mock_queries'"}]}