Django:TypeError-类型“ QuerySet”的参数不可迭代

时间:2018-08-30 19:35:34

标签: 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)

我不知道这是否相关,但这是在芹菜任务中发生的,并且错误已在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有关。 (请参阅最后三个回复)

1 个答案:

答案 0 :(得分:1)

也许您应该在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