ManyRelatedManager object is not iterable

Django

Django Problem Overview


Trying to do this:

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

And get this...

'ManyRelatedManager' object is not iterable

Both fields are many-to-many so how can this be done?

Django Solutions


Solution 1 - Django

Try

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

Notice the parenthesis at the end of WishList.attribute_answers.all(). Adding the parenthesis invokes the all function to return an iterable.

If you include the parenthesis you're saying "give me all the values in the stores answers so long as that value is also in the wish lists answers". Without the parenthesis you're asking for all the values from the store's answers that are also in the all function, which is meaningless. The all function is not an iterable (it's a function that returns an iterable)

Solution 2 - Django

Sounds like you are looking for something like

Store.attribute_answers.all()

Solution 3 - Django

If you are doing this in a template:

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

UPDATE

If you have a through table, you can access the elements in that table (as detailed here) like so (note, you use the through table name, in lowercase, suffixing _set):

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

Solution 4 - Django

>>>all()

For everyone who finds reading code in questions as TL;DR

Instead of query_set.many_to_many

you should use query_set.many_to_many.all()

Solution 5 - Django

I keep hitting this question whenever this problem comes up. Particularly when trying to actually iterate over a manytomany in a function.

As a template you can do:

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

Solution 6 - Django

Here busines_type is foreign_key in profile model

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjasonView Question on Stackoverflow
Solution 1 - DjangoAidan EwenView Answer on Stackoverflow
Solution 2 - DjangosecondView Answer on Stackoverflow
Solution 3 - DjangoandywView Answer on Stackoverflow
Solution 4 - DjangoQbackView Answer on Stackoverflow
Solution 5 - DjangoAlex TomlinsonView Answer on Stackoverflow
Solution 6 - DjangoNids BarthwalView Answer on Stackoverflow