Oct 26, 2011

Django: 'ManyRelatedManager' object is not iterable

Upon development proces you often meet ManyToMany relations that throw errors in templates. I prefer to feed everything to context and play with it there.

This kind of error appears when you iterate through a model's ManyToMany field. To fix it just add a related 'all' manager through dot syntax. Like so:

Model:

class BannerImage(models.Model):
    image = models.ImageField(upload_to="somedir")

    def get_image_url(self):
        return 'Image url here'

class Banner(models.Model):
    name = models.CharField(max_length=250, null=True)
    images = models.ManyToManyField(BannerImage)


View/Tag or else, that creates context:

banner = get_object_or_404(Banner, pk=1)
return {'banner': banner,}


Template causing the error:

{% for image in banner.images %}
    <img src="{{ image.get_image_url }}" />
{% endfor %}


Template without the error:

{% for image in banner.images.all %}
    <img src="{{ image.get_image_url }}" />
{% endfor %}


I wrote this article for myself for remembering. I always forget this little thing. But if this method works for your case fill free to drop a "thankyou" comment or +1.


1 comment: