【问题标题】:Trying to compare non-ordered queryset against more than one ordered values django尝试将无序查询集与多个有序值 django 进行比较
【发布时间】:2017-08-03 20:20:12
【问题描述】:

此单元测试失败,但出现以下异常:

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: 试图将无序查询集与多个有序值进行比较

我做错了什么?

【问题讨论】:

    标签: python django unit-testing django-queryset


    【解决方案1】:

    来自docs

    默认情况下,比较也取决于顺序。如果 qs 不提供隐式排序,您可以将 ordered 参数设置为 False,这会将比较转换为 collections.Counter 比较。如果顺序未定义(如果给定的 qs 未排序并且比较针对多个有序值),则会引发 ValueError。

    您将QuerySetlist 进行比较。 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)
    

    在比较之前重新排序查询集也应该有效。

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2020-07-08
      相关资源
      最近更新 更多