comparing querysets in django TestCase

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

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)

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)


This alternative doesn't need sorting:

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

See the assert reference.

Note: Only for django 1.4+.