zerohedge
zerohedge

Reputation: 3725

Django: TypeError - argument of type 'QuerySet' is not iterable

So this error is very cryptic, how can it be that a Queryset object, even if empty, is not iterable?

This is the rare error I'm seeing:

TypeError: argument of type 'QuerySet' is not iterable

And this is the code producing this error:

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)

I don't know if this is relevant, but this is happening in a celery task and the error is being reported in Sentry (an exception reporting service).

Traceback that I have:

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:

Update: not sure, but I think this related to this issue on the Django forums. (see last three replies)

Upvotes: 8

Views: 6102

Answers (2)

anibal
anibal

Reputation: 439

I faced the same problem, using the "in" operator I got the error message "QuerySet is not iterable", after changing my code to the "exists" version, I realize that I forgot a migration (the error message changed to "table does not exist"). Didn't try, but I guess that if I revert the change, now that the migration was applied, no error will be raised.

My conclusion: The "in" operator works, but is harder to debug in rare situations (when a migration is missing, for example), then, it's better to use the uglier "exists" version.

Upvotes: 0

ocobacho
ocobacho

Reputation: 551

Maybe you should use a filter in the if. instead of: if rg not in artist_release_groups: artist_object.release_groups.add(rg)

use

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

Upvotes: 1

Related Questions