Skip to content

Instantly share code, notes, and snippets.

@jdunck
Created November 20, 2014 20:10
Show Gist options
  • Save jdunck/db81a1adbfd7c5428ffd to your computer and use it in GitHub Desktop.
Save jdunck/db81a1adbfd7c5428ffd to your computer and use it in GitHub Desktop.
As efficient a QuerySet.__contains__ as can be mustered.
def instance_in_qs(instance_or_pk, qs):
if qs._result_cache is None:
if qs.query.can_filter():
pk = getattr(instance_or_pk, 'pk', instance_or_pk)
return qs.filter(pk=pk).exists()
else:
objs = list(qs)
else:
objs = qs._result_cache
if hasattr(instance_or_pk, 'pk'):
return instance_or_pk in objs
else:
get_pk = lambda o: getattr(o, 'pk')
return instance_or_pk in map(get_pk, objs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment