Login

Work around for negation of Q filter

Author:
LLyaudet
Posted:
March 31, 2022
Language:
Python
Version:
3.2
Score:
0 (after 0 ratings)

It may save you some time if you're in the case of this link : https://stackoverflow.com/questions/11801363/django-q-with-joins-functioning-incorrectly-bug

It worked for me at least.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def put_Q_negations_to_leaves(
    query_filter: Q,
    negate: bool = False,
    debug: bool = False,
):
    negate_below = (negate != query_filter.negated)  # XOR
    if debug:
        logger.info(
            f"put_Q_negations_to_leaves() query_filter:{query_filter}"
            f" negate:{negate} negate_below:{negate_below}"
        )
    true_kwargs = {
        "_connector": query_filter.connector,
        "_negated": False,
    }
    new_children = []
    for child in query_filter.children:
        if debug:
            logger.info(child.__repr__())
        if not isinstance(child, Q):
            if negate_below:
                new_child = ~Q(child)
            else:
                new_child = child
        else:
            new_child = put_Q_negations_to_leaves(child, negate=negate_below)
        if debug:
            logger.info(new_child.__repr__())
        new_children.append(new_child)
    if len(new_children) == 1:
        # One child
        if isinstance(new_children[0], Q):
            return new_children[0]
        else:
            true_kwargs["_negated"] = negate_below
    if negate_below:
        if true_kwargs["_connector"] == Q.AND:
            true_kwargs["_connector"] = Q.OR
        else:
            true_kwargs["_connector"] = Q.AND
    return Q(*new_children, **true_kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

LLyaudet (on March 31, 2022):

It took me a few hours to code it and I may have forgot some special cases. Be sure to test in your specific use case.

#

Please login first before commenting.