Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: ManyRelatedManager object is not iterable

Tags:

python

django

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)
like image 827
Bharath Pabba Avatar asked Aug 19 '17 05:08

Bharath Pabba


1 Answers

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.

like image 179
Arpit Solanki Avatar answered Sep 16 '22 15:09

Arpit Solanki