您的位置:首页 > 移动开发 > Objective-C

DJANGO问题--Error: ‘ManyRelatedManager’ object is not iterable

2016-02-23 11:14 1896 查看
http://www.itblah.com/django-error-manyrelatedmanager-object-iterable/

Django: Error: ‘ManyRelatedManager’ object is not iterable

While trying to iterate through a list of objects in a Django template, I came across this error: “Caught an exception while rendering: ‘ManyRelatedManager’ object is not iterable”

Also of note is in the variables “<django.db.models.fields.related.ManyRelatedManager object at 0x9876545>” is returned rather than the value of that object.

To clarify, i’m trying to print a list of objects “Items” associated with a model “Things” through a ManyToMany relationship.
You may have guest, but I’ve changed the actual model names to help protect my project.

Lets take a look at the model:

class Thing(models.Model):
# Comment
def __unicode__(self): # Python 3: def __str__(self):
return self.name

name = models.CharField(max_length=32)
desc = models.CharField(max_length=254)
img = models.CharField(max_length=32)
items = models.ManyToManyField(Measurement)
category = models.ManyToManyField(Category)

Lets take a look at the template:

If “my_things” exists, we’re going to create a list of all the objects it contains.
If the “my_things” object contains any “items”, these will be listed in a nested list.
Well, thats the plan. In RED i’ve highlighted the reasons it fails.


{% if my_things %}
<ul>
{% for thing in my_things %}
<li>{{ thing }}</li>
<ul>
{% for item in things.items %}
<li>{{ thing.item }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
{% else %}


How to fix “‘ManyRelatedManager’ object is not iterable” error:
Note the changes in RED


{% if my_things %}
<ul>
{% for thing in my_things %}
<li>{{ thing }}</li>
<ul>
{% for item in things.items.all %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endfor %}
</ul>
{% else %}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: