python config_error ai_generated true

RuntimeError: Database access not allowed, use the 'django_db' mark or the 'db' or 'transactional_db' fixtures to enable it.

ID: python/pytest-django-db-access-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
91%Confidence
0Evidence
2024-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.x active

Root Cause

pytest-django blocks database access by default in tests to prevent accidental queries. The test attempts to query the database without the required marker or fixture.

generic

中文

pytest-django 默认在测试中阻止数据库访问,以防止意外查询。测试在未使用所需标记或夹具的情况下尝试查询数据库。

Workarounds

  1. 95% success
    import pytest
    
    @pytest.mark.django_db
    def test_user_creation():
        User.objects.create(username='test')
        assert User.objects.count() == 1
  2. 93% success
    def test_user_creation(db):
        User.objects.create(username='test')
        assert User.objects.count() == 1

Dead Ends

Common approaches that don't work:

  1. 90% fail

    This flag only skips migrations, it does not disable the database access blocker. The RuntimeError persists.

  2. 65% fail

    This enables database access for all tests, slowing down the suite and hiding tests that should not hit the database.