Bitwise aggregates (BitAnd, BitOr, BitXor over flags=1..10)

Django ORM PostgreSQL May 22, 2026 python

Fold an integer column with bitwise operators across each group: BitOr sets a bit if *any* row has it, BitAnd only if *all* do, and BitXor toggles.

python
 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
# ======================================================================
# Fold an integer column with bitwise operators across each group: `BitOr` sets
# a bit if *any* row has it, `BitAnd` only if *all* do, and `BitXor` toggles.
# Handy for packed flag columns.
# ======================================================================

# --- Django ORM ---
Measurement.objects.values("series").annotate(
    b_and=BitAnd("flags"),
    b_or=BitOr("flags"),
    b_xor=BitXor("flags"),
).order_by("series")

# --- generated SQL ---
#   SELECT "examples_measurement"."series" AS "series", BIT_AND("examples_measurement"."flags") AS "b_and", BIT_OR("examples_measurement"."flags") AS "b_or", BIT_XOR("examples_measurement"."flags") AS "b_xor"
#   FROM "examples_measurement"
#   GROUP BY 1
#   ORDER BY 1 ASC

# ----------------------------------------------------------------------
# series 'linear'
# ----------------------------------------------------------------------

# Result:
#   bit_and=0 (0b0000)  bit_or=15 (0b1111)  bit_xor=11 (0b1011)

# ----------------------------------------------------------------------
# series 'noisy'
# ----------------------------------------------------------------------

# Result:
#   bit_and=0 (0b0000)  bit_or=15 (0b1111)  bit_xor=11 (0b1011)