Typeerror: Manyrelatedmanager Object Is Not Iterable

I am not able to resolve the error named Many Related Manager is not iterable. I have Models named A and B as shown below:

class B(models.Model):
     indicator = models.CharField(max_length=255, null=True)
     tags = models.CharField(max_length=255, null=True, blank=True)


class A(models.Model):
     definitions = models.ManyToManyField(B)
     user = models.ForeignKey('userauth.ABCUSER', null=True, blank=True)
     project = models.ForeignKey('userauth.ProjectList', null=True, blank=True)

I want to retrieve definitions attribute of Model A which includes attributes of Class B. I have tried to retrieve it as shown below, But It gives me an error:

TypeError: ManyRelatedManager object is not iterable

 if tbl_scope == 'Generic':
        checked_objects = A.objects.get(user=user, project=project)


 for checked_object in checked_objects.definitions:
        print(checked_object.indicator)

1 Answer

An m2m field is returned as a related manager object so its not iterable. You need to use all to convert it to a queryset to make it iterable.

if tbl_scope == 'Generic':
        checked_objects = A.objects.get(user=user, project=project)


 for checked_object in checked_objects.definitions.all():
        print(checked_object.indicator)

You can read more about m2m field.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest