Last active
December 20, 2015 00:29
-
-
Save jsatt/6042104 to your computer and use it in GitHub Desktop.
Class for dynamically generating a Django QuerySet from a list of Django objects of the same type.
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
from django.db.models.query import QuerySet | |
class QuerySetFromIter(QuerySet): | |
def __init__(self, objects=[], model=None, query=None, *args, **kwargs): | |
if model is None: | |
if len(objects): | |
model = type(objects[0]) | |
else: | |
# TODO: find a better way to handle this | |
raise ValueError( | |
'If objects is empty, a model must be included') | |
pk_list = [] | |
for r in objects: | |
if not type(r) is model: | |
raise TypeError('All objects must be the same model') | |
pk_list.append(r.id) | |
super(QuerySetFromIter, self).__init__(model, query, *args, **kwargs) | |
self._result_cache = list(objects) | |
self.query.add_filter(('pk__in', pk_list)) | |
def _clone(self, klass=None, setup=False, **kwargs): | |
if klass is None: | |
klass = self.__class__.__base__ | |
return super(QuerySetFromIter, self)._clone(klass, setup, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment