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

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 %}

你可能感兴趣的:(DJANGO问题--Error: ‘ManyRelatedManager’ object is not iterable)