python config_error ai_generated true

Failed:不允许访问数据库,请使用 "django_db" 标记或 "db"/"transactional_db" fixture 来启用。

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

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

版本兼容性

版本状态引入弃用备注
4.8 active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 80% 失败

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