在Django TestCase中比较查询集 [英] comparing querysets in django TestCase

查看:73
本文介绍了在Django TestCase中比较查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的视图,如下所示

I have a very simple view as follows

def simple_view(request):
    documents = request.user.document_set.all()
    return render(request, 'simple.html', {'documents': documents})

要在我的测试用例中测试以上视图,我有以下方法会出错。

To test the above view in my test case i have the following method which errors out.

Class SomeTestCase(TestCase):
    # ...
    def test_simple_view(self):
        # ... some other checks
        docset = self.resonse.context['documents']
        self.assertTrue(self.user.document_set.all() == docset) # This line raises an error
    # ...

我得到的错误是 AssertionError:假不是真的
我尝试打印两个查询集,并且两个都完全相同。当两个对象相同时,为什么返回 False ?有任何想法吗?

The error i get is AssertionError: False is not true. I have tried printing both the querysets and both are absolutely identical. Why would it return False when both the objects are identical ? Any Ideas ?

当前为了克服这个问题,我正在使用一种讨厌的方法来检查长度,如下所示:

Currently to overcome this, I am using a nasty hack of checking lengths as follows:

ds1, ds2 = self.response.context['documents'], self.user.document_set.all()
self.assertTrue(len([x for x in ds1 if x in ds2]) == len(ds1) == len(ds2)) # Makes sure each entry in ds1 exists in ds2


推荐答案

queryset对象是不同查询的结果,即使它们的结果相同(即使 ds1.query ds2.query )。

The queryset objects will not be identical if they are the result of different queries even if they have the same values in their result (compare ds1.query and ds2.query).

如果转换查询集首先到列表,您应该能够进行常规比较(假设它们当然具有相同的排序顺序):

If you convert the query set to a list first, you should be able to do a normal comparison (assuming they have the same sort order of course):

self.assertEqual(list(ds1), list(ds2))

这篇关于在Django TestCase中比较查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆