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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值