【问题标题】:ManyRelatedManager object is not iterableManyRelatedManager 对象不可迭代
【发布时间】:2013-02-17 11:48:33
【问题描述】:

尝试这样做:

wishList = WishList.objects.get(pk=20)
matches = [val for val in Store.attribute_answers.all() if val in wishList.attribute_answers]

然后得到这个...

'ManyRelatedManager' object is not iterable

这两个字段都是多对多的,如何做到这一点?

【问题讨论】:

    标签: django


    【解决方案1】:

    试试

    matches = [val for val in Store.attribute_answers.all() if val in WishList.attribute_answers.all()]
    

    注意WishList.attribute_answers.all() 末尾的括号。添加括号会调用all 函数以返回一个可迭代对象。

    如果您包含括号,您的意思是“给我商店答案中的所有值,只要该值也在愿望清单答案中”。如果没有括号,您将要求商店答案中的所有值也在 all 函数中,这是没有意义的。 all 函数不是可迭代的(它是一个返回可迭代的函数)

    【讨论】:

      【解决方案2】:

      all()

      对于所有在TL;DR

      的问题中发现阅读代码的人

      而不是query_set.many_to_many

      你应该使用 query_set.many_to_many.all()

      【讨论】:

      • 这应该是公认的答案,再简单不过了
      【解决方案3】:

      听起来你正在寻找类似的东西

      Store.attribute_answers.all()
      

      【讨论】:

        【解决方案4】:

        如果您在模板中执行此操作:

        {% for room in study.room_choice.all %}
          {{ room }}
          {% empty %}
          empty list!
        {% endfor %}
        

        更新

        如果您有一个直通表,您可以像这样访问该表中的元素(详细说明here)(注意,您使用直通表名称,小写,后缀_set):

        {% for roominfo in participant.roomchoicethru_set.all %}
          {{ roominfo.room}} {{ roominfo.telnumber}}
        {% endfor %}
        

        【讨论】:

          【解决方案5】:

          每当出现这个问题时,我都会不断提出这个问题。尤其是在尝试实际迭代函数中的多态时。

          作为模板你可以这样做:

          array = many_to_many.all()
          for x in many_to_many:
            function here
          

          【讨论】:

            【解决方案6】:

            这里的 busines_type 是 profile 模型中的 foreign_key

            pro = Profile.object.filter(user=myuser).first()
            business_type = pro.business_type.all()
            if business_type:
                b_type = ''
                for b in business_type:
                    b_type += str(b.type)+' '
                    a = b_type
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-07-17
              • 1970-01-01
              • 1970-01-01
              • 2019-11-12
              • 2017-01-05
              相关资源
              最近更新 更多