Created
November 20, 2014 20:10
-
-
Save jdunck/db81a1adbfd7c5428ffd to your computer and use it in GitHub Desktop.
As efficient a QuerySet.__contains__ as can be mustered.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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