此单元测试失败,但出现以下异常:
def test_vote_form_with_multiple_choices_allowed_and_submitted(self):
"""
If multiple choices are allowed and submitted, the form should be valid.
"""
vote_form = VoteForm({'choice': [1, 2]}, instance=create_question('Dummy question', -1,
[Choice(choice_text='First choice'), Choice(
choice_text='Second choice')],
allow_multiple_choices=True))
self.assertTrue(vote_form.is_valid())
self.assertQuerysetEqual(vote_form.cleaned_data['choice'], ['<Choice: First choice>', '<Choice: Second choice>'])
ValueError:尝试将非有序查询集与多个有序值进行比较 我做错了什么?
答案 0 :(得分:8)
来自docs:
默认情况下,比较也依赖于排序。如果qs不提供隐式排序,则可以将ordered参数设置为False,从而将比较转换为collections.Counter比较。如果订单未定义(如果给定的qs没有排序并且比较针对多个有序值),则会引发ValueError。
您正在将QuerySet
与list
进行比较。列表有一个排序,但Queryset没有。
因此您可以将QuerySet转换为列表
queryset = vote_form.cleaned_data['choice']
self.assertQuerysetEqual(list(queryset), ['<Choice: First choice>', ...])
或将ordered=False
传递给assertQuerysetEqual
。
queryset = vote_form.cleaned_data['choice']
self.assertQuerysetEqual(list(queryset), ['<Choice: First choice>', ...], ordered=False)
在比较之前重新排序Queryset也应该有效。