Django - 可怕的'非序列迭代

1 投票
1 回答
810 浏览
提问于 2025-04-16 03:16

你好,我想根据俱乐部的来源来填充一个成员列表。

这是我的代码:

 members = []
 if userprofile.countries.count() > 0:
     for c in userprofile.countries.all():
         clubs = Club.objects.filter(location__country = c)
         for club in clubs:
             members_list = Member.objects.get_members(club)
             for m in members_list:
                 members.append(m)

但是,当我执行 for m in members_list: 这行代码时,出现了“对非序列进行迭代”的错误。

我不太确定为什么会这样?有没有人能给我一些建议?!

编辑:

我用以下方法解决了这个问题:

members = []
if userprofile.countries.count() > 0:
            members_list = member.objects.filter(memberstoentities__club__location__country__in = userprofile.countries.all())
            for m in members_list:
                members.append(m)

1 个回答

2

我无法评论,除非查看会员模型。不过,

  1. 我们能不能用 .filter 结合反向导航,而不是用 get_members?
  2. 我们真的需要那么多循环吗?而且在循环里访问数据库?比如:

clubs = Club.objects.filter(location__country__in = list_of_user_countries)

如果你最后想要的列表是会员的列表,你可以像我上面提到的那样做(至少是更优化的方式)

撰写回答