Django returns 测试中的空 QuerySet

Django returns empty QuerySet in the tests

我正在尝试对此视图进行测试:

def author_detail(request, pk):
    author = get_object_or_404(Author, pk=pk)
    blog = author.blog_set.all()

    paginator = Paginator(blog, 1)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'author': author,
        'page_obj': page_obj,
    }

    return render(request, 'blog/author_detail.html', context=context)

视图运行正常。我的问题是什么时候我要尝试测试这个视图。这是我的测试:

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')

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

    # The author.blog_set.all() are returning an empty QuerySet
    # This problem are only happening in the tests, not in the view
    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)

结果是:

FAIL: test_pagination_first_page (blog.tests.test_views.AuthorDetailViewTest)
-------------------------------------------------------------------
Traceback (most recent call last):
   File "/home/carlos/problem/venv_01/the_blog/blog/tests/test_views.py", line 189,in test_pagination_first_page
       self.assertEqual(len(response.context['page_obj']), 1)
AssertionError: 0 != 1
----------------------------------------------------------------------

len(response.context['page_obj'])等于0,至少应该是1,因为我创建了一个Blog对象。当我打印 author.blog_set.all() 的 QuerySet 时,返回的 QuerySet 为空 ()。我认为问题出在博客模型的创建上,因为作者和主题字段是 ManyToManyField.

正如我之前提到的,我的问题是在测试中,而不是在视图中。视图工作正常。

以下代码片段的最后 3 行存在一些问题:

    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')

        Blog.objects.create(title='My blog', content="It's my blog")
        Blog.author = self.author_instance
        Blog.topic = topic
  • 博客对象已创建但从未创建returned/fetched
  • 正在使用博客模型连接作者和主题。相反,应该使用 blog 对象。
  • 作者和主题是博客上的 M2M。应通过 add 方法添加新对象。有关其他上下文,请参阅 How to add data into ManyToMany field?

解决方案:

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

    author = Author.objects.create(
        user=user, date_of_birth='1998-09-08', bio='I am user01')
    
    blog = Blog.objects.create(
            title='My blog', content="It's my blog")
    blog.author.add(author)
    blog.topic.add(topic)

成功了。