Skip to content

Instantly share code, notes, and snippets.

@balazs-endresz
Last active August 29, 2015 14:00
Show Gist options
  • Save balazs-endresz/1afb4a73e25b74b03c62 to your computer and use it in GitHub Desktop.
Save balazs-endresz/1afb4a73e25b74b03c62 to your computer and use it in GitHub Desktop.
QuerySetChain
from itertools import islice, chain
class QuerySetChain(object):
"""
Chains multiple subquerysets (possibly of different models) and behaves as
one queryset. Supports minimal methods needed for use with
django.core.paginator.
http://stackoverflow.com/questions/431628/how-to-combine-2-or-more-querysets-in-a-django-view#answer-432666
"""
def __init__(self, *subquerysets):
self.querysets = subquerysets
def count(self):
"""
Performs a .count() for all subquerysets and returns the number of
records as an integer.
"""
return sum(qs.count() for qs in self.querysets)
def _clone(self):
"Returns a clone of this queryset chain"
return self.__class__(*self.querysets)
def _all(self):
"Iterates records in all subquerysets"
return chain(*self.querysets)
def __getitem__(self, ndx):
"""
Retrieves an item or slice from the chained set of results from all
subquerysets.
"""
if type(ndx) is slice:
return list(islice(self._all(), ndx.start, ndx.stop, ndx.step or 1))
else:
return islice(self._all(), ndx, ndx+1).next()
@seenureddy
Copy link

Hi this is working Fine. But if we want additional methods like filter and exclude on this multiple qurey set chain is possible. if possible can you help me to find way to write.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment