python config_error ai_generated true

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

ID: python/pytest-django-database-access-not-allowed

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
4.8 active

Root Cause

pytest-django blocks DB access by default to keep tests fast and isolated. Any ORM call in a test without @pytest.mark.django_db or the db fixture raises this failure.

generic

中文

pytest-django 默认阻止数据库访问,以保持测试快速且隔离。任何没有 @pytest.mark.django_db 或 db fixture 的 ORM 调用都会引发此失败。

Workarounds

  1. 97% success
    import pytest
    
    @pytest.mark.django_db
    def test_create_user():
        User.objects.create(email='[email protected]')
        assert User.objects.count() == 1
  2. 96% success
    def test_create_user(db):
        User.objects.create(email='[email protected]')
        assert User.objects.count() == 1

Dead Ends

Common approaches that don't work:

  1. 90% fail

    The block is enforced by pytest-django's plugin, not by the database backend; the failure occurs before any connection is attempted.

  2. 80% fail

    NameError: name 'pytest' is not defined, or the mark is silently ignored if imported incorrectly.