You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django使用嵌套Factory工厂出现Database access not allowed错误如何解决

问题排查与解决方法

1. 先修复UserProfileFactory的错误定义

你当前在UserProfileFactory的类属性中直接调用UserFactory.create(),这段代码会在模块导入阶段就执行,此时测试框架还没完成初始化、没有开放数据库访问权限,会提前触发数据库访问报错。
正确写法是用SubFactory声明关联工厂,只有当你主动调用UserProfileFactory.create()时才会生成关联的User对象:

from factory import SubFactory # 新增导入

class UserProfileFactory(DjangoModelFactory):
    user = SubFactory(UserFactory) # 替换原有的UserFactory.create()
    country = Faker("country") # 适用法律
    birth_date = Faker("date_of_birth") # 美国禁止收集13岁以下儿童数据

    class Meta:
        model = UserProfile

2. 给测试用例开启数据库访问权限

根据你使用的测试框架二选一即可:

方案A:使用pytest测试框架

给测试方法加django_db标记,允许该用例访问数据库:

import pytest
from rest_framework.test import APIRequestFactory
# 补充你需要的其他导入

class TestUserProfileDetailView():
    @pytest.mark.django_db # 新增装饰器
    def test_create_userprofile(self):
        """创建APIRequest,使用UserProfile实例测试user_detail_view视图"""
        factory = APIRequestFactory()
        request = factory.get('/api/userprofile/')
        # 注意:request.user是Django原生User实例,不能直接赋值UserProfile
        user_profile = UserProfileFactory.create()
        request.user = user_profile.user
        response = user_detail_view(request)
        self.assertEqual(response.status_code, 200)

方案B:使用Django原生测试框架

让测试类继承django.test.TestCase,Django原生TestCase会自动给所有测试用例开放数据库访问权限:

from django.test import TestCase
from rest_framework.test import APIRequestFactory
# 补充你需要的其他导入

class TestUserProfileDetailView(TestCase): # 继承TestCase
    def test_create_userprofile(self):
        """创建APIRequest,使用UserProfile实例测试user_detail_view视图"""
        factory = APIRequestFactory()
        request = factory.get('/api/userprofile/')
        user_profile = UserProfileFactory.create()
        request.user = user_profile.user
        response = user_detail_view(request)
        self.assertEqual(response.status_code, 200)

内容的提问来源于stack exchange,提问作者Back2Basics

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:54:03