Django - 返回对象时,ManyRelatedManager对象不可迭代

5

在将一些项目添加到我的“国家”ManyToManyField后,我无法返回对象。 我可以看到我的数据已保存

class CompanyProfileManager(models.Manager):
    @transaction.atomic
    def register_company(self, name, description, tag_name, email, is_private, uses_credits, pays_subscription, pool,
                     facebook, twitter, web, country, videocall_doctor_to_patient, micro_type, can_move, fixed_percentage, fixed_price, fixed_tariff, instagram, subdomain, banner_description, banner_title, countries,  **kwargs):
        tag = Tag(name=tag_name, description=tag_name, is_active=True)
        tag.save()

        company = self.create_instance(name, description, email, is_private, uses_credits, pays_subscription, pool,
                                   facebook, twitter, web, country, videocall_doctor_to_patient, micro_type, can_move, fixed_percentage, fixed_price, fixed_tariff, instagram, subdomain, banner_description, banner_title)

        company.tag = tag
        company.save()

        for item in countries:
            company.countries.add(item)

        return company #Using Debug Mode, My project breaks right here

我真的很迷茫,到目前为止,我所看到与我的问题相关的唯一内容是使用.all()作为查询集

1个回答

13

许多对多属性(在您的情况下为countries)是Manager,更确切地说是ManyRelatedManager而不是QuerySet。有点像QuerySet.objects中的objects,因此如果要遍历所有国家,您需要使用.all()

for item in countries.all():
    company.countries.add(item)

你也可以使用其他高级方法,如.filters().select_related()等...

编辑

由于变量countries不是查询集而是列表,我怀疑错误并不是由这段代码生成的,很可能是在你尝试迭代company.countries而不是company.countries.all()之后发生的。


我收到了“list”对象没有属性“all”的错误。 - BrianCas
修改了答案。 - Cyrlop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接