Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate over ManyToManyField?

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 ?

like image 736
Goro Avatar asked Mar 05 '12 22:03

Goro


2 Answers

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

like image 176
Abid A Avatar answered Oct 21 '22 13:10

Abid A


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

for t in myStuff.things.all():
    print t.myStuffs.all()
like image 39
niko.makela Avatar answered Oct 21 '22 12:10

niko.makela