Skip to content

cache_keys

Cache keys of statement templates: hashable values holding everything about a queryset that changes its SQL text and none of its bound values.

Two querysets with equal keys must build the same SQL, or one would run the other's statement. QuerySet.select_cache_key combines these keys for reads, QuerySet.build_write_template for filtered updates and deletes::

Text Only
1
2
Author.objects.filter(name="a")  # same key as filter(name="b")
Author.objects.filter(name=None)  # different key: renders IS NULL

action_cache_key(action)

Return everything about a filter action that changes the SQL text: the field path, the table alias of the joined relation, the operator, the kind of value (see value_cache_key) and whether LIKE needs an ESCAPE clause for % or _ in the value.

Parameters:

Name Type Description Default
action FilterAction

filter action

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the action

Source code in ormar/queryset/templates/cache_keys.py
Python
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def action_cache_key(action: "FilterAction") -> Tuple[Any, ...]:
    """
    Return everything about a filter action that changes the SQL text: the
    field path, the table alias of the joined relation, the operator, the
    kind of value (see ``value_cache_key``) and whether LIKE needs an ``ESCAPE``
    clause for ``%`` or ``_`` in the value.

    :param action: filter action
    :type action: FilterAction
    :return: hashable cache key of the action
    :rtype: Tuple[Any, ...]
    """
    return (
        action.query_str,
        action.table_prefix,
        action.operator,
        value_cache_key(action=action),
        action.has_escaped_character,
    )

clauses_cache_key(clauses)

Return the cache key of a list of filter actions and filter groups, keeping the and/or/not nesting, since or_(a, b) and and_(a, b) build different SQL from the same actions::

Text Only
1
2
filter(ormar.or_(name="a", score=1))
# -> (("group", FilterType.OR, False, (), (<name key>, <score key>)),)

Parameters:

Name Type Description Default
clauses Iterable[Any]

filter actions and filter groups

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the clauses

Source code in ormar/queryset/templates/cache_keys.py
Python
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def clauses_cache_key(clauses: Iterable[Any]) -> Tuple[Any, ...]:
    """
    Return the cache key of a list of filter actions and filter groups, keeping
    the and/or/not nesting, since ``or_(a, b)`` and ``and_(a, b)`` build
    different SQL from the same actions::

        filter(ormar.or_(name="a", score=1))
        # -> (("group", FilterType.OR, False, (), (<name key>, <score key>)),)

    :param clauses: filter actions and filter groups
    :type clauses: Iterable[Any]
    :return: hashable cache key of the clauses
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (
            "group",
            clause.filter_type,
            clause.exclude,
            clauses_cache_key(clauses=clause._nested_groups),
            tuple(action_cache_key(action=action) for action in clause.actions),
        )
        if hasattr(clause, "_nested_groups")
        else action_cache_key(action=clause)
        for clause in clauses
    )

excludable_cache_key(excludable)

Return the fields included and excluded per model and relation, which decide the selected columns (fields(), exclude_fields(), values()). Field sets are sorted so the same selection always gives the same key.

Parameters:

Name Type Description Default
excludable ExcludableItems

queryset's fields to include and exclude

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the projection

Source code in ormar/queryset/templates/cache_keys.py
Python
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def excludable_cache_key(excludable: "ExcludableItems") -> Tuple[Any, ...]:
    """
    Return the fields included and excluded per model and relation, which
    decide the selected columns (``fields()``, ``exclude_fields()``,
    ``values()``). Field sets are sorted so the same selection always gives
    the same key.

    :param excludable: queryset's fields to include and exclude
    :type excludable: ExcludableItems
    :return: hashable cache key of the projection
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (
            key,
            tuple(sorted(item.include, key=repr)),
            tuple(sorted(item.exclude, key=repr)),
            tuple(sorted(item.flatten, key=repr)),
            item.pk_only,
        )
        for key, item in sorted(excludable.items.items())
    )

order_cache_key(order_bys)

Return the cache key of the requested orderings: field path, direction, table alias and nulls placement of each, in order::

Text Only
1
order_by("-name")  # -> (("-name", "desc", "", None),)

Parameters:

Name Type Description Default
order_bys Iterable[OrderAction]

order actions of the query

required

Returns:

Type Description
Tuple[Any, ...]

hashable cache key of the ordering

Source code in ormar/queryset/templates/cache_keys.py
Python
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def order_cache_key(order_bys: Iterable["OrderAction"]) -> Tuple[Any, ...]:
    """
    Return the cache key of the requested orderings: field path, direction, table
    alias and nulls placement of each, in order::

        order_by("-name")  # -> (("-name", "desc", "", None),)

    :param order_bys: order actions of the query
    :type order_bys: Iterable[OrderAction]
    :return: hashable cache key of the ordering
    :rtype: Tuple[Any, ...]
    """
    return tuple(
        (order.query_str, order.direction, order.table_prefix, order.nulls_ordering)
        for order in order_bys
    )

value_cache_key(action)

Return the part of a filter value that changes the SQL text::

Text Only
1
2
3
4
5
6
filter(name__isnull=True)  # -> ("isnull", True)   IS NULL
filter(name=None)  # -> ("literal", None)  IS NULL
filter(active=True)  # -> ("literal", True)  literal true
filter(id__in=[1, 2])  # -> "in"               IN (expanding)
filter(name="a")  # -> ("value", str)     = :ormar_p0
filter(a__lt=F("b") + 1)  # -> ("expr", <shape>)  < b + :ormar_p0_0

Values written into the SQL text are part of the key as they are. For a bound value only its type is kept, so values of different types never share a statement.

Parameters:

Name Type Description Default
action FilterAction

filter action

required

Returns:

Type Description
Any

hashable value kind

Source code in ormar/queryset/templates/cache_keys.py
Python
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def value_cache_key(action: "FilterAction") -> Any:
    """
    Return the part of a filter value that changes the SQL text::

        filter(name__isnull=True)  # -> ("isnull", True)   IS NULL
        filter(name=None)  # -> ("literal", None)  IS NULL
        filter(active=True)  # -> ("literal", True)  literal true
        filter(id__in=[1, 2])  # -> "in"               IN (expanding)
        filter(name="a")  # -> ("value", str)     = :ormar_p0
        filter(a__lt=F("b") + 1)  # -> ("expr", <shape>)  < b + :ormar_p0_0

    Values written into the SQL text are part of the key as they are. For a
    bound value only its type is kept, so values of different types never
    share a statement.

    :param action: filter action
    :type action: FilterAction
    :return: hashable value kind
    :rtype: Any
    """
    value = action.bound_value()
    if isinstance(value, Expression):
        return ("expr", expression_key(node=value))
    if action.operator == "isnull":
        return ("isnull", bool(value))
    if action.operator == "in":
        return "in"
    if not action.binds_slot():
        return ("literal", value)
    return ("value", type(value))