[英]Django TypeError: 'RelatedManager' object is not iterable
I have these Django models:我有这些 Django 型号:
class Group(models.Model):
name = models.CharField(max_length=100)
parent_group = models.ManyToManyField("self", blank=True)
def __unicode__(self):
return self.name
class Block(models.Model):
name = models.CharField(max_length=100)
app = models.CharField(max_length=100)
group = models.ForeignKey(Group)
def __unicode__(self):
return self.name
Lets say that block b1 has the g1 group.假设块b1具有g1组。 By it's name I want to get all blocks from group g1 .
按它的名字,我想从组g1中获取所有块。 I wrote this recursive function:
我写了这个递归 function:
def get_blocks(group):
def get_needed_blocks(group):
for block in group.block_set:
blocks.append(block)
if group.parent_group is not None:
get_needed_blocks(group.parent_group)
blocks = []
get_needed_blocks(group)
return blocks
But b1.group.block_set returns a RelatedManager object, which is not iterable.但是b1.group.block_set返回一个RelatedManager object,它是不可迭代的。
What am I doing wrong and how can I fix it?我做错了什么,我该如何解决?
Try this:尝试这个:
block in group.block_set.all()
Use it like a Manager
.像
Manager
一样使用它。 If you want all the objects then call the all()
method.如果您想要所有对象,请调用
all()
方法。
you have to use.all() with related name or childModel_set model name.您必须使用相关名称或 childModel_set model 名称的 use.all()。
in views.py use:在views.py 中使用:
for item in object.relatedname.all():
do something ......
in html templates use:在 html 模板中使用:
{% for item in object.relatedname.all %}
do something ......
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.