Monday, July 14, 2008

'ManyRelatedManager' object is not iterable

When I'm writing an app ,in fact it's just a test.following is the actually code:
{% if query%}
{%for book in results%}

{{book.title}}


{%for author in book.authors%}
  • {{author.first_name}}|{{author.last_name}}

  • {%endfor%}

    {{book.publisher.name}}

    {%endfor%}
    {%else%}
  • No Books Found

  • {%endif%}

    When I run it.I got an error message:
    'ManyRelatedManager' object is not iterable.

    the solution for this is

    change the for loop syntax to:

    {%for author in book.authors.all%}

    then it'll be done.

    19 comments:

    1. This comment has been removed by the author.

      ReplyDelete
    2. The ManyRelatedManager object have a "all" method that returns the children array:

      Example:

      If you are defined a child list like this:

      class myParent(models.Model):
      aChildList = ManyToMany('myChildModel')

      then, for read this list of child attribute do:

      tmpChildList = myParent.aChildList.all()
      for myChild in tmpChildList:
      print myChild.name # if name is a field of the child

      best regards!

      ReplyDelete
    3. Superhelpful. Thanks for posting.

      ReplyDelete
    4. thank you thank you thank you thank you thank you thank you thank you

      ReplyDelete
    5. Great info. Please note that in the original post, all is used as a property. As Jean Machuca pointed out this is actually a method e.g. all()

      ReplyDelete
    6. This comment has been removed by the author.

      ReplyDelete
    7. Thanks! This is the first result when Googling "manyrelatedmanager". Nice.

      ReplyDelete
    8. So helpful for long time yet, thank you for sharing.
      greetings from Brazil.

      ReplyDelete
    9. nice one - this saved me some time

      ReplyDelete