[英]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:我有一个带有 ManyToMany 字段的模型:
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 ?如何迭代 manyToManyField ?
尝试添加()
all
: myStuff.things.all()
Like Abid A already answered, you are missing brackets ()就像 Abid A 已经回答了一样,您缺少括号 ()
for t in myStuff.things.all():
print t.myStuffs.all()
ManyToManyField seems to have a different kind of Manager than your basic Django class. ManyToManyField 似乎有一种与您的基本 Django 类不同的 Manager。 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.在这里查看源代码https://github.com/django/django/blob/master/django/db/models/fields/related_descriptors.py#L821 ,您似乎正在寻找 related_val 字段,该字段似乎包含相关对象引用的元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.