简体   繁体   中英

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 ?

尝试添加() allmyStuff.things.all()

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM