[Answer]-How to empty a Django Queryset

1👍

If you’re using Django <= 1.5, you can subclass both the EmptyQuerySet class and your own custom queryset class. Just override none() to return your custom class:

class MyQuerySet(QuerySet):
    def none(self):
        # prevent circular import
        from . import MyEmptyQuerySet
        return self._clone(klass=MyEmptyQuerySet)

class MyEmptyQuerySet(EmptyQuerySet, MyQuerySet):
    pass

In Django 1.6, the class of your queryset is still the same if you call none(), but through use of metaclasses and overriding __instancecheck__, calling isinstance(qs.none(), EmptyQuerySet) will still return True. So in Django 1.6, there is no need for custom classes or anything, your new methods on your custom queryset class are still available on an empty queryset.

👤knbk

0👍

qs = qs.filter_by_name(name).filter_by_color(color)
qs = qs.filter_by_date(date) if isinstance(qs, MyQuerySet) else qs

That’s the simplest thing I can see right now. Or filter by color at the end of the chain.

Leave a comment