[Django]-Comparing querysets in django TestCase

42πŸ‘

βœ…

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

10πŸ‘

This alternative doesn’t need sorting:

self.assertQuerysetEqual(qs1, list(qs2), ordered=False)

See the assert reference.

Note: Only for django 1.4+.

2πŸ‘

You can use the assertQuerysetEqual method to compare two querysets without casting to a list. This will return True if the values of the querysets are equal, regardless of if the queries are different.

One gotcha is that this method applies the repr function as a transform to each object in the first argument before comparing, which can result in the following error when comparing two actually equal querysets:

AssertionError: Lists differ: ['<Object: id1'] != [<Object: id1>]

The solution is to pass your own transform function to use instead of repr:

self.assertQuerysetEqual(qs1, qs2, transform=lambda x: x)

2πŸ‘

if you want to check that Django querysets are completely the same

self.assertEqual(str(simple_qs.query), str(complex_qs.query))

1πŸ‘

For me works the transform option:

    def subject(self):
        return Mission.objects.add_keynest_api_token().filter(keynest_api_token__isnull=False)

    def test_mission_has_property(self):
        self.mission.appartement = self.property
        self.mission.save()
        self.assertQuerysetEqual(self.subject(), [self.mission], transform=lambda x: x)

0πŸ‘

If you’d like to assert that the content of two querysets is equal without worrying about the order, use the following:

self.assertQuerysetEqual(actual_queryset, expected_queryset, transform=lambda x: x, ordered=False)

-1πŸ‘

Found a solution. We need to convert Querysets to sorted lists before we can compare them. Something as follows.

Class SomeTestCase(TestCase):
    # ...
    def test_simple_view(self):
        # ... some other checks
        docset1 = self.resonse.context['documents']
        docset2 = self.user.document_set.all()
        self.assertTrue(list(sorted(docset1)) == len(sorted(docset)))
    # ...

-1πŸ‘

def test_simple_view(self):
    # ... some other checks
    docset = set([i.pk for i in self.resonse.context['documents']])
    prev = set([i.pk for i in self.user.document_set.all()])
    diff = prev.difference(docset)
    self.assertTrue(len(diff)==0)

Leave a comment