Django TypeError: 'RelatedManager' object is not iterable
Question:
I have these Django models:
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. By it’s name I want to get all blocks from group g1. I wrote this recursive 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.
What am I doing wrong and how can I fix it?
Answers:
Try this:
block in group.block_set.all()
Use it like a Manager
. If you want all the objects then call the all()
method.
you have to use .all() with related name or childModel_set model name .
in views.py use :
for item in object.relatedname.all():
do something ......
in html templates use:
{% for item in object.relatedname.all %}
do something ......
{% endfor %}
I have these Django models:
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. By it’s name I want to get all blocks from group g1. I wrote this recursive 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.
What am I doing wrong and how can I fix it?
Try this:
block in group.block_set.all()
Use it like a Manager
. If you want all the objects then call the all()
method.
you have to use .all() with related name or childModel_set model name .
in views.py use :
for item in object.relatedname.all():
do something ......
in html templates use:
{% for item in object.relatedname.all %}
do something ......
{% endfor %}