python config_error ai_generated true

RuntimeError: 不允许访问数据库,请使用 'django_db' 标记或 'db' 或 'transactional_db' 夹具来启用。

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

其他格式: JSON · Markdown 中文 · English
80%修复率
91%置信度
0证据数
2024-02-14首次发现

版本兼容性

版本状态引入弃用备注
4.x active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 65% 失败

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