ManyRelatedManager object is not iterable

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?


Solution 1:

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:

Sounds like you are looking for something like

Store.attribute_answers.all()