python runtime_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-fixture-db-access

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

pytest-django blocks database access by default. The test tries to query the database without the django_db mark or db fixture.

generic

中文

pytest-django 默认阻止数据库访问。测试尝试查询数据库但没有使用 django_db 标记或 db fixture。

Workarounds

  1. 98% success
    @pytest.mark.django_db
    def test_create_user():
        User.objects.create(username='test')
  2. 95% success
    def test_create_user(db):
        User.objects.create(username='test')
  3. 90% success
    @pytest.mark.django_db(transaction=True)
    def test_transaction():
        ...

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The block is enforced by pytest-django, not Django settings.

  2. 95% fail

    Breaks Django test integration and may cause other failures.

  3. 80% fail

    pytest-django still applies the block unless marked.