How can I iterate over ManyToManyField?

PythonDatabaseDjangoOrmModel

Python Problem Overview


A simple question and yet I can't find an answer for it.

I have a model with a ManyToMany field:

class Stuff(models.Model):
  things = models.ManyToManyField(Thing)

then in a different function I want to do this:

myStuff = Stuff.objects.get(id=1)
for t in myStuff.things.all:
  # ...

But that is giving me:

TypeError: 'instancemethod' object is not iterable

How can I iterate over a manyToManyField ?

Python Solutions


Solution 1 - Python

Try adding the () after all: myStuff.things.all()

Solution 2 - Python

Like Abid A already answered, you are missing brackets ()

for t in myStuff.things.all():
    print t.myStuffs.all()

Solution 3 - Python

ManyToManyField seems to have a different kind of Manager than your basic Django class. Looking at the source here, https://github.com/django/django/blob/master/django/db/models/fields/related_descriptors.py#L821, it seems you are looking for the related_val field which appears to contain the tuple of related objects references.

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
QuestionGoroView Question on Stackoverflow
Solution 1 - PythonAbid AView Answer on Stackoverflow
Solution 2 - Pythonniko.makelaView Answer on Stackoverflow
Solution 3 - PythonjshView Answer on Stackoverflow