[Django]-'RelatedManager' object is not iterable Django

230👍

Call all() to retrieve the elements from the manager.

{% for area in world_areas.all %}

15👍

In general, it is better practice to use a values or values_list to pass data from a queryset to a template.

world_areas = Areas.objects.select_related().all().values_list('name', 'order_in_sidebar_network', ...)

Check out the Django docs for info on how to use the values function if you haven’t used it before.

10👍

I run into this issue by a reckless mistake:

 for physicalserver in task.physicalservers:
        physicalserver.relieve_task()

The task.physicalservers is RelatedManager object, in my case I should get the task’s physicalservers, there should add .all().

for physicalserver in task.physicalservers.all():

1👍

You have to iterate over set to get values related to a fk in a model.

class Area(models.Model):
    name =  models.CharField(max_length = 120)
    order_in_sidebar_network = models.IntegerField(blank=True, null=True)
    order_in_section_network = models.IntegerField(blank=True, null=True)


class CountryArea(models.Model):
    name = models.CharField(max_length = 120)
    area = models.ForeignKey(Area, verbose_name = 'Area')

 ## Assuming you have an object; area
 ## To get the all the counties related to that area you can do;
    {% for obj in area.countryarea_set.all %}
        <h4> {{ obj.name }} </h4>
    {% endfor %}
👤7guyo

Leave a comment