最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Django出错:TypeError: object of type ‘ManyRelatedManager’ has no len()

TypeError crifan 1890浏览 0评论
折腾:
【未解决】Django中如何查询一个对象包含于一个列表内均可
期间,用代码:
class FunctionGroup(TimestampedModel):
    
members = models.ManyToManyField(User)

        elif groupId:
            passInGroup = FunctionGroup.objects.get(pk=groupId)
            logger.info("passInGroup=%s", passInGroup)
            if passInGroup:
                memberList = passInGroup.members
                logger.info("memberList=%s", memberList)
                filterAuthorList = memberList
结果出错:
 File "/Users/crifan/dev/dev_root/company/xxx/projects/xxx/server/xxx/apps/script/views.py", line 118, in list
    logger.info("len=%d, filterAuthorList=%s", len(filterAuthorList), filterAuthorList)
TypeError: object of type 'ManyRelatedManager' has no len()
其中看到log中memberList是:
memberList=user.User.None
所以先要去:
搞清楚ManyToManyField,如何获取单个对象
TypeError: object of type ‘ManyRelatedManager’ has no len()
Django TypeError: object of type ‘ManyRelatedManager’ has no len()
解决django “TypeError:object of type ‘type’ has no len()”问题 – CSDN博客
TypeError: object of type ‘Query’ has no len() · Issue #29 · Suor/django-cacheops
python – TypeError: object of type ‘Cursor’ has no len() – Stack Overflow
python – TypeError: object of type ‘EmailMultiAlternatives’ has no len() – Stack Overflow
Django TypeError ManyRelatedManager  has no len()
Django: ‘ManyRelatedManager’ object is not iterable
后面要加个:.all() 好像才行
去试试
memberList = passInGroup.members.all()
期间又出现:
【已解决】Antd Pro中始终显示loading加载无法完成消失掉
然后才可以继续测试上面的api的代码:
是正常工作的,返回User的list:
memberList=<QuerySet [<User: xxx>, <User: Maggie>, <User: xxx>]>
后来在其他帖子也看到了同样的说法,加上.adll()即可:
django – ManyRelatedManager not Iterable. Think I’m trying to pull my objects out incorrectly – Stack Overflow
对于many-to-many field,需要用.all()才能获取所有对象的列表
同时:many-to-many field是个manager -》 也就可以用querysets去获取对应的值了 -〉 所以此处用最常见的.all()即可获取内容 -》扩展:如果想要加上filter过滤参数,也是可以的。
Help: Custom ManyRelatedManager Behavior – Google Groups
【总结】
对于定义中的:
class FunctionGroup(TimestampedModel):
    members = models.ManyToManyField(User)
想要获取FunctionGroup的members的User的列表,需要注意的是:
直接通过:
passInGroup.members
得到的只是ManyRelatedManager对象,是个manager管理工具,所以没有len,所以报错:
TypeError: object of type 'ManyRelatedManager' has no len()
而manager的话,就和其他之前遇到的类似,支持queryset,所以可以用:
passInGroup.members.all()
即可得到User的列表
-》同时,如果需要加上其他filter的参数的话,也是可以的,比如:
passInGroup.members.all(pk=someUserId)

转载请注明:在路上 » 【已解决】Django出错:TypeError: object of type ‘ManyRelatedManager’ has no len()

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
80 queries in 0.162 seconds, using 22.14MB memory