Django: remove a filter condition from a queryset

Although there is no official way to do this using filter notation, you may easily do it with Q-notation. For example, if you ensure that third-part function returns a Q object, not a filtered QuerySet, you may do the following:

q = ThirdParty()
q = q | Q(valid=False)

And the resulting SQL conditions will be joined using OR operator.


From the docs:

Each time you refine a QuerySet, you get a brand-new QuerySet that is in no way bound to the previous QuerySet. Each refinement creates a separate and distinct QuerySet that can be stored, used and reused.

I doubt therefore, that there is a standard way to do it. You could dig into the code, see, what filter() does and try a bit. If that doesn't help, my assumption is, you're out of luck and need to re-build the query yourself.


Use this function

from django.db.models import Q

def remove_filter(lookup, queryset):
    """
    Remove filter lookup in queryset
    ```
    >>> queryset = User.objects.filter(email='[email protected]')
    >>> queryset.count()
    1
    >>> remove_filter('email', queryset)
    >>> queryset.count()
    1000
    ```
    """
    query = queryset.query
    q = Q(**{lookup: None})
    clause, _ = query._add_q(q, self.used_aliases)

    def filter_lookups(child):
        return child.lhs.target != clause.children[0].lhs.target

    query.where.children = list(filter(filter_lookups, query.where.children))