python
config_error
ai_generated
true
RuntimeError: 不允许访问数据库,请使用 "django_db" 标记,或使用 "db" 或 "transactional_db" fixture 以启用。
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
80%修复率
90%置信度
0证据数
2024-04-27首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 4.x | active | — | — | — |
根因分析
pytest-django 默认阻止数据库访问以保持测试快速。任何未带 django_db 标记或 db fixture 的 ORM 查询都会引发此错误。
English
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.
解决方案
-
98% 成功率
import pytest @pytest.mark.django_db def test_user_count(): from myapp.models import User assert User.objects.count() == 0 -
95% 成功率
def test_user_count(db): from myapp.models import User assert User.objects.count() == 0
无效尝试
常见但无效的做法:
-
85% 失败
That variable is for async ORM access, not for pytest-django's DB access guard.
-
80% 失败
Django is already set up; the guard is enforced by pytest-django at the connection level.