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-not-allowed

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.x active

Root Cause

pytest-django blocks DB access by default to keep tests fast. Any ORM query in a test without the django_db marker or db fixture raises this error.

generic

中文

pytest-django 默认阻止数据库访问以保持测试快速。任何未带 django_db 标记或 db fixture 的 ORM 查询都会引发此错误。

Workarounds

  1. 98% success
    import pytest
    
    @pytest.mark.django_db
    def test_user_count():
        from myapp.models import User
        assert User.objects.count() == 0
  2. 95% success
    def test_user_count(db):
        from myapp.models import User
        assert User.objects.count() == 0

Dead Ends

Common approaches that don't work:

  1. 85% fail

    That variable is for async ORM access, not for pytest-django's DB access guard.

  2. 80% fail

    Django is already set up; the guard is enforced by pytest-django at the connection level.