How do I test Django QuerySets are equal?
By default assertQuerysetEqual
uses repr()
on the first argument. This is why you were having issues with the strings in the queryset comparison.
To work around this you can override the transform
argument with a lambda
function that doesn't use repr()
:
self.assertQuerysetEqual(queryset_1, queryset_2, transform=lambda x: x)
Use assertQuerysetEqual, which is built to compare the two querysets for you. You will need to subclass Django's django.test.TestCase
for it to be available in your tests.
I just had the same problem. The second argument of assertQuerysetEqual
needs to be a list of the expected repr()s as strings. Here is an example from the Django test suite:
self.assertQuerysetEqual(c1.tags.all(), ["<Tag: t1>", "<Tag: t2>"], ordered=False)