python - Django:TypeError - 'QuerySet' 类型的参数不可迭代

标签 python django

所以这个错误很神秘,怎么可能是Queryset对象,即使是空的,也不是可迭代的吗?

这是我看到的罕见错误:

TypeError: argument of type 'QuerySet' is not iterable

这是产生此错误的代码:
artist_object = Artist.objects.get(id=id)
artist_release_groups = artist_object.release_groups.all()
if rg not in artist_release_groups: # this is the line where the error is  happening
    artist_object.release_groups.add(rg)

我不知道这是否相关,但这是在 celery 任务中发生的,并且在 Sentry(异常报告服务)中报告了错误。

我拥有的回溯:
TypeError: argument of type 'QuerySet' is not iterable
  File "celery/app/trace.py", line 382, in trace_task
    R = retval = fun(*args, **kwargs)
  File "celery/app/trace.py", line 641, in __protected_call__
    return self.run(*args, **kwargs)
  File "core/tasks.py", line 234, in refresh_artist_task
    get_apple_release_groups_for_artist(applemusic_id)
  File "celery/local.py", line 191, in __call__
    return self._get_current_object()(*a, **kw)
  File "celery/app/trace.py", line 642, in __protected_call__
    return orig(self, *args, **kwargs)
  File "celery/app/task.py", line 375, in __call__
    return self.run(*args, **kwargs)
  File "core/tasks.py", line 147, in get_apple_release_groups_for_artist
    if rg not in artist_release_groups:

更新:不确定,但我认为这与 this issue on the Django forums 有关. (见最后三个回复)

最佳答案

也许您应该在 if 中使用过滤器。
代替: if rg not in artist_release_groups: artist_object.release_groups.add(rg)

artist_release_groups_query = artist_object.release_groups.filter(id=rg.id)
if not artist_rease_groups_query.exists():
    # add the rest

关于python - Django:TypeError - 'QuerySet' 类型的参数不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104224/

相关文章:

python - 类型错误 : an integer is required python

javascript - 我可以将 JS 脚本放在页脚上方而不是页脚下方 </body> 标记之前吗

python - 如何在 Python 中使用正则表达式和 re.sub 查找所有出现的 unicode 字符的大写和小写字母?

python - 基于 child 数量的Django查询集过滤器

python - 查找一段时间内每个项目和 ID 的平均值 (Python)

python - 在 Python 中求解 x 的高度非线性方程

python - self 未在类方法参数中定义

python - 将代码的基本部分从 C++ 转换为 Python

python - Django 原始查询

python - Django 添加 GenericForeignKey 搜索字段