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

Django单元测试中author.blog_set.all()返回空QuerySet问题

问题解决方法

核心错误原因

  • 你调用Blog.objects.create()创建实例后没有接收返回的实例对象,反而直接对Blog模型类本身赋值author和topic属性,该赋值操作不会同步到数据库中已创建的Blog记录,导致数据库里的Blog没有关联任何作者,自然无法通过author.blog_set.all()查询到数据。
  • 若Blog的author、topic字段为ManyToManyField类型,多对多关联需要通过Django提供的关联方法操作中间表,不能直接赋值字段实现关联。

修改后的测试代码(仅需调整setUp方法中Blog创建部分)

class AuthorDetailViewTest(TestCase):
    def setUp(self):
        user = User.objects.create(username='user01', password='123456')

        self.author_instance = Author.objects.create(
            user=user, date_of_birth='1998-09-08', bio='I am user01')

        topic = Topic.objects.create(name='Testing')

        # 接收create返回的新建Blog实例
        blog = Blog.objects.create(title='My blog', content="It's my blog")
        # 多对多字段绑定关联
        blog.author.add(self.author_instance)
        blog.topic.add(topic)
        # 显式保存实例同步到数据库
        blog.save()

    def test_pagination_first_page(self):
        response = self.client.get(
            reverse('author-detail', kwargs={'pk':self.author_instance.pk}))
        self.assertEqual(len(response.context['page_obj']), 1)

额外说明

如果后续你调整业务逻辑,把Blog的author字段改为ForeignKey(一个博客仅对应一个作者的场景更常用该字段类型),可以直接在创建实例时传入关联对象,写法更简洁:

Blog.objects.create(
    title='My blog', 
    content="It's my blog",
    author=self.author_instance,
    topic=topic
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:06:07