62

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 ?

Goro
  • 9,919
  • 22
  • 74
  • 108
  • "instancemethod object" should have tipped you off that it's a method (needs parentheses), not an iterable. – mpen Mar 05 '12 at 23:21

3 Answers3

114

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

Abid A
  • 7,588
  • 4
  • 32
  • 32
2

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

for t in myStuff.things.all():
    print t.myStuffs.all()
niko.makela
  • 537
  • 3
  • 14
  • 3
    why'd you repeat it then? and your example is broken... what are you trying to print (there's a colon at the end)? – mpen Mar 05 '12 at 23:19
  • 2
    By then I did not have a permission to write comments here and my purpose was to show a real working example of for-loop printing the things all stuffs that you was not able to show. A colon is there because in Python a for-loop always needs one! – niko.makela Nov 15 '13 at 08:14
  • I believe I was referring to the extra colon you edited out. But fair enough... I do find complete examples easier to follow. – mpen Nov 15 '13 at 16:38
0

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.

jsh
  • 1,995
  • 18
  • 28