Trying to compare non-ordered queryset against more than one ordered values

If you are writing unit tests in Django 1.6 or later, and using assertQuerysetEqual, you may get the following error message:

ValueError: Trying to compare non-ordered queryset against more than one ordered values

If so, you are probably trying to do something like this inside a unit test:

self.assertQuerysetEqual(response.context['products'], ['<Product: marmite>', '<Product: ketchup>'])

This happens because the Queryset (in response.context[‘products’]) has no particular ordering, but the list you’re comparing it to does. As of Django 1.6, assertQuerysetEqual doesn’t support this type of comparison. The quickest way to get around this issue is to explicitly order the Queryset. This should match the ordering of your list of expected values:

self.assertQuerysetEqual(response.context['products'].order_by('product_name'), ['<Product: marmite>', '<Product: ketchup>'])