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

如何在pytest-django中统计模型对象数量?测试返回0的问题排查

问题原因与解决方案
  • 核心原因:pytest运行测试时会使用独立的测试数据库,这个数据库默认是空的,和你在python manage.py shell中使用的开发数据库完全分离,所以测试里查询不到现有数据。

  • 解决方案1:手动在测试中创建数据
    修改测试代码,在断言前生成需要的测试对象:

    import pytest
    from .models import Organization
    
    @pytest.mark.django_db
    def test_organization():
        # 创建10个测试用Organization对象(替换为你的模型实际字段)
        for i in range(10):
            Organization.objects.create(name=f"测试组织{i}")
        assert Organization.objects.count() == 10
    
  • 解决方案2:使用Django Fixture加载预定义数据

    1. 先从开发数据库导出数据到fixture文件:
      python manage.py dumpdata myapp.Organization --indent 2 > myapp/fixtures/organizations.json
      
    2. 在测试中加载fixture数据:
      import pytest
      from django.core.management import call_command
      from .models import Organization
      
      @pytest.fixture
      def load_org_data():
          call_command("loaddata", "organizations.json")
      
      @pytest.mark.django_db
      def test_organization(load_org_data):
          assert Organization.objects.count() == 10
      
  • 注意事项:禁止让测试直接使用开发数据库,这会破坏测试隔离性,导致结果不稳定,还可能污染开发数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 11:42:35