TypeError:ManyRelatedManager对象不可迭代

时间:2022-01-05 20:22:59

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:

我无法解决名为Many Related Manager不可迭代的错误。我有名为A和B的模型,如下所示:

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:

我想检索模型A的定义属性,其中包含类B的属性。我试图检索它,如下所示,但它给了我一个错误:

TypeError: ManyRelatedManager object is not iterable

TypeError:ManyRelatedManager对象不可迭代

 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 个解决方案

#1


12  

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.

m2m字段作为相关管理器对象返回,因此不可迭代。您需要使用all将其转换为查询集以使其可迭代。

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.

您可以阅读有关m2m字段的更多信息。

#1


12  

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.

m2m字段作为相关管理器对象返回,因此不可迭代。您需要使用all将其转换为查询集以使其可迭代。

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.

您可以阅读有关m2m字段的更多信息。