Django Code Snippets

Powered by PythonAnywhere and Django 1.8.6

Remove Clause from QuerySet

Date Added: Nov. 12, 2015, 4:13 p.m.

Author: django-snippets



from django.db.models.sql.where import *

__all__ = ['remove_clause', ]


def remove_clause(queryset, field_name):
    # Start the recursive fixin'
    _remove_clause(queryset.query.where, field_name)


def _remove_clause(node, field_name):
    if isinstance(node, WhereNode):
        null_these = []
        # look at each child and treat appropriately
        for i, child in enumerate(node.children):
            if isinstance(child, WhereNode):
                _remove_clause(child, field_name)
            elif isinstance(child, tuple) and isinstance(child[0], Constraint):
                if child[0].field.name == field_name:
                    null_these.append(i)

        # we have some children to "nullify"
        for null_this in null_these:
            if node.connector == 'AND':
                node.children[null_this] = EverythingNode()
            else:
                node.children[null_this] = NothingNode()

 

Tags: django, python

Return to List