A simple question and yet I can't find an answer for it.
一个简单的问题,我却找不到答案。
I have a model with a ManyToMany field:
我有一个模型,有很多的tomany领域:
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 ?
如何遍历一个多字段?
3 个解决方案
#1
66
Try adding the ()
after all
: myStuff.things.all()
尝试添加()毕竟:myStuff.things.all()
#2
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.
与基本的Django类不同,许多tomanyfield似乎有一种不同的管理器。在这里查看源代码,https://github.com/django/blob/master/django/db/models/fields/related_descriptors.py #L821,似乎您正在寻找related_val字段,该字段似乎包含相关对象引用的元组。
#3
-2
Like Abid A already answered, you are missing brackets ()
就像Abid A已经回答的那样,您缺少了方括号()
for t in myStuff.things.all():
print t.myStuffs.all()
#1
66
Try adding the ()
after all
: myStuff.things.all()
尝试添加()毕竟:myStuff.things.all()
#2
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.
与基本的Django类不同,许多tomanyfield似乎有一种不同的管理器。在这里查看源代码,https://github.com/django/blob/master/django/db/models/fields/related_descriptors.py #L821,似乎您正在寻找related_val字段,该字段似乎包含相关对象引用的元组。
#3
-2
Like Abid A already answered, you are missing brackets ()
就像Abid A已经回答的那样,您缺少了方括号()
for t in myStuff.things.all():
print t.myStuffs.all()