Permalink
Fetching contributors…
Cannot retrieve contributors at this time
135 lines (88 sloc) 3.89 KB

Aggregates

MySQL-specific database aggregates for the ORM.

The following can be imported from django_mysql.models.

Returns an int of the bitwise AND of all input values, or 18446744073709551615 (a BIGINT UNSIGNED with all bits set to 1) if no rows match.

Docs: MySQL / MariaDB.

Example usage:

>>> Book.objects.create(bitfield=29)
>>> Book.objects.create(bitfield=15)
>>> Book.objects.all().aggregate(BitAnd('bitfield'))
{'bitfield__bitand': 13}

Returns an int of the bitwise OR of all input values, or 0 if no rows match.

Docs: MySQL / MariaDB.

Example usage:

>>> Book.objects.create(bitfield=29)
>>> Book.objects.create(bitfield=15)
>>> Book.objects.all().aggregate(BitOr('bitfield'))
{'bitfield__bitor': 31}

Returns an int of the bitwise XOR of all input values, or 0 if no rows match.

Docs: MySQL / MariaDB.

Example usage:

>>> Book.objects.create(bitfield=11)
>>> Book.objects.create(bitfield=3)
>>> Book.objects.all().aggregate(BitXor('bitfield'))
{'bitfield__bitxor': 8}

An aggregate that concatenates values from a column of the grouped rows. Useful mostly for bringing back lists of ids in a single query.

Docs: MySQL / MariaDB.

Example usage:

>>> from django_mysql.models import GroupConcat
>>> author = Author.objects.annotate(
...     book_ids=GroupConcat('books__id')
... ).get(name="William Shakespeare")
>>> author.book_ids
"1,2,5,17,29"

Warning

MySQL will truncate the value at the value of group_concat_max_len, which by default is quite low at 1024 characters. You should probably increase it if you're using this for any sizeable groups.

group_concat_max_len docs: MySQL / MariaDB.

Optional arguments: